Ein Idempotenzschlüssel für Zahlungen
Ein Client bekam wegen eines Timeouts keine Antwort auf „100 $ abbuchen“ und versucht es erneut. Um nicht doppelt abzubuchen, nehmen solche APIs einen Header Idempotency-Key an. Schreib withIdempotency(handler, { ttlMs, now }), das (key, payload) => Promise liefert.
- Der erste Aufruf mit einem Schlüssel führt handler(payload) aus; gleichzeitige Aufrufe mit demselben Schlüssel bekommen währenddessen dasselbe Promise.
- Ein erfolgreiches Ergebnis wird ttlMs lang gemerkt und ohne erneuten Aufruf des Handlers geliefert.
- Ein Fehler wird nicht gemerkt: der nächste Aufruf mit dem Schlüssel versucht es erneut.
- Derselbe Schlüssel mit anderem payload (verglichen mit JSON.stringify) wird mit Idempotency key reused with a different payload abgelehnt.
Strg+Enter führt die Tests aus. Tab rückt ein; um den Editor per Tastatur zu verlassen, drücke Esc und dann Tab. Der Code wird in diesem Browser gespeichert.
Tests (6)
let t = 0; const charge = fn(async (p) => ({ id: 'ch_1', amount: p.amount })); const pay = withIdempotency(charge, { ttlMs: 60_000, now: () => t }); const first = await pay('key-1', { amount: 100 }); const second = await pay('key-1', { amount: 100 }); expect(second).toEqual(first); expect(charge).toHaveBeenCalledTimes(1);
let t = 0; const charge = fn(async (p) => { await wait(20); return p.amount; }); const pay = withIdempotency(charge, { ttlMs: 60_000, now: () => t }); const results = await Promise.all([pay('k', { amount: 5 }), pay('k', { amount: 5 }), pay('k', { amount: 5 })]); expect(results).toEqual([5, 5, 5]); expect(charge).toHaveBeenCalledTimes(1);
let t = 0; const pay = withIdempotency(async (p) => p.amount, { ttlMs: 60_000, now: () => t }); await pay('k', { amount: 100 }); await expect(pay('k', { amount: 999 })).rejects.toThrow('different payload');
let t = 0; let calls = 0; const pay = withIdempotency(async () => { calls++; if (calls === 1) throw new Error('gateway timeout'); return 'ok'; }, { ttlMs: 60_000, now: () => t }); await expect(pay('k', {})).rejects.toThrow('gateway timeout'); expect(await pay('k', {})).toBe('ok'); expect(calls).toBe(2);
let t = 0; const charge = fn(async () => 'ok'); const pay = withIdempotency(charge, { ttlMs: 1000, now: () => t }); await pay('k', {}); t = 999; await pay('k', {}); expect(charge).toHaveBeenCalledTimes(1); t = 1000; await pay('k', {}); expect(charge).toHaveBeenCalledTimes(2);
let t = 0; const charge = fn(async (p) => p.n); const pay = withIdempotency(charge, { ttlMs: 1000, now: () => t }); expect(await pay('a', { n: 1 })).toBe(1); expect(await pay('b', { n: 2 })).toBe(2); expect(charge).toHaveBeenCalledTimes(2);