# 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.

```bash
bun install --frozen-lockfile
bun run example:refund
```

It shows four cases:

1. A new refund returns `succeeded` and happens once.
2. The same request sent again returns the saved result, and the provider is not called again.
3. A provider that completes the refund but then loses its reply returns `unknown`.
4. A provider that declines the refund up front returns `failed`, because the capability throws `knownFailure()`.

## Capability

```ts
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.

## Source

- [`examples/refund/src/app.ts`](https://github.com/hiyoriOS/kaji/blob/main/examples/refund/src/app.ts)
- [`examples/refund/src/payments.ts`](https://github.com/hiyoriOS/kaji/blob/main/examples/refund/src/payments.ts)