Refund example
A runnable example with a fake payment provider.
The Kaji repository includes a runnable refund example in examples/refund. Run these commands from a clone of the repository. It uses a fake payment provider and exits with an error if any check fails.
bun install --frozen-lockfile
bun run example:refund
It shows four cases:
- A new refund returns
succeededand happens once. - The same request sent again returns the saved result, and the provider is not called again.
- A provider that completes the refund but then loses its reply returns
unknown. - A provider that declines the refund up front returns
failed, because the capability throwsknownFailure().
Capability
const refund = capability({
name: "payments.refund",
input: RefundInput,
authorize: ({ principalId, input }) => canRefund(principalId, input.paymentId),
approval: ({ input }) => input.amount >= 500,
execute: async (input, context) => {
try {
return await payments.refund({
...input,
idempotencyKey: context.idempotencyKey,
signal: context.signal,
});
} catch (cause) {
if (cause instanceof PaymentDeclinedError) throw knownFailure(cause);
throw cause;
}
},
});
const kaji = createKaji({
store: memoryStore(),
approve: async () => ({ approved: true }),
});
The example approves everything automatically. A real app would ask a person or an approval service.
The capability passes idempotencyKey to the provider as well. Kaji stops duplicate calls to execute, and the provider’s own key stops duplicate refunds if execute is ever retried.