Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

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.

JavaScript
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'));
}
Text
{ 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.

Also inAPIs
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.