Origit Console
IBM Bob connected acme-payments · Business plan · demo
acme-payments/payments-api PublicBusiness
main payments-api/src/settlement.ts
26 lines · 686 bytes sha256 31cb991741b6b4edd9c1 month ago
import { Payment } from './types';

const BACKOFF_MS = [10, 20, 40];
const MAX_ATTEMPTS = 3;

export function defaultDelay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function settle(
  payment: Payment,
  send: (p: Payment) => Promise<void>,
  delay: (ms: number) => Promise<void> = defaultDelay,
): Promise<Payment> {
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
    try {
      await send(payment);
      return { ...payment, status: 'settled' };
    } catch {
      if (attempt < MAX_ATTEMPTS - 1) {
        await delay(BACKOFF_MS[attempt]);
      }
    }
  }
  return { ...payment, status: 'failed' };
}
Powered by IBM Bob 2.0