Implement the adapter pattern for two APIs
Implement the adapter pattern for two APIs in JavaScript: wrap each payment SDK in the same small interface. Node.js 24.
Two libraries do the same job with different method names and shapes. An adapter wraps each one so the rest of your code talks to a single interface.
class OldPayments {
charge(dollars, card) {
return { ok: true, id: 'old-1', amount: dollars };
}
}
class NewPayments {
createPayment({ amountCents, source }) {
return { status: 'succeeded', id: 'new-1', amountCents };
}
}
const fromOld = (api) => ({
pay(cents, card) {
const result = api.charge(cents / 100, card);
return { ok: result.ok, id: result.id };
},
});
const fromNew = (api) => ({
pay(cents, card) {
const result = api.createPayment({ amountCents: cents, source: card });
return { ok: result.status === 'succeeded', id: result.id };
},
});
for (const gateway of [fromOld(new OldPayments()), fromNew(new NewPayments())]) {
console.log(gateway.pay(1250, 'tok_1'));
}{ ok: true, id: 'old-1' }
{ ok: true, id: 'new-1' }Both adapters expose pay(cents, card) and return { ok, id }. The old SDK wants dollars and the new one wants cents, and that conversion is done inside the adapter, in one place. The calling code never learns which SDK is behind the gateway.
This makes a migration a swap of one adapter. Keep the shared interface small, only what your code needs, or the adapters turn into copies of the libraries they wrap.