Skip to content
jshacks.dev
Patterns

The Adapter Pattern in JavaScript, With Real Examples

The adapter pattern converts one interface into another so incompatible code can work together. See API, library and legacy adapters in JavaScript with tests.

8 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, Node.js, Vite and npm logos.

The adapter pattern wraps an object or a function so that it presents the interface your code expects, even though the thing underneath speaks a different one. The name comes from the travel plug: the socket and the device do not change, and a small piece in between makes them fit. In JavaScript you meet the problem constantly: a payment provider returns snake_case fields while your domain uses camelCase, two logging libraries have different method names, a legacy callback API must feed new promise-based code. An adapter keeps the mismatch in one place so the rest of the program never sees it. This post shows adapters for an API response, a third-party library and a callback API, plus the two-way and class-based variants, testing and the limits of the pattern, on Node.js 24. Every sample prints its output.

The problem: someone else's shape

Imagine your code expects payments to look like this: { id, amountCents, currency, status }. A provider returns a different shape.

provider-shape.mjsJavaScript
const providerResponse = {
  payment_id: "pay_42",
  amount: "19.99",
  currency_code: "usd",
  state: "SETTLED",
};

function receipt(payment) {
  return `${payment.id}: ${payment.amountCents / 100} ${payment.currency} (${payment.status})`;
}

console.log(receipt(providerResponse));
Text
undefined: NaN undefined (undefined)

None of the field names match, so receipt prints nonsense. You could change receipt, but then every function that consumes payments must also learn the provider's vocabulary, and when you add a second provider, each of them must learn two. The adapter confines the translation to one function.

An adapter function

payment-adapter.mjsJavaScript
const STATUS = { SETTLED: "paid", PENDING: "pending", FAILED: "failed" };

export function fromProvider(response) {
  return {
    id: response.payment_id,
    amountCents: Math.round(Number(response.amount) * 100),
    currency: response.currency_code.toUpperCase(),
    status: STATUS[response.state] ?? "unknown",
  };
}

function receipt(payment) {
  return `${payment.id}: ${payment.amountCents / 100} ${payment.currency} (${payment.status})`;
}

const payment = fromProvider({ payment_id: "pay_42", amount: "19.99", currency_code: "usd", state: "SETTLED" });
console.log(payment);
console.log(receipt(payment));
Text
{ id: 'pay_42', amountCents: 1999, currency: 'USD', status: 'paid' }
pay_42: 19.99 USD (paid)

The adapter does four jobs: renames fields, converts the decimal string into integer cents, normalizes the currency and maps the status vocabulary, with unknown as the safe fallback for values it has never seen. Everything past this function sees only your shape. When the provider changes state to status, one function changes. This is the same idea as an anti-corruption layer in domain-driven design.

Adapting a whole library

Often the mismatch is not data but behavior. Suppose your application logs through an interface { info, error } and you want to use a library whose methods are write(level, message, meta).

logger-adapter.mjsJavaScript
// The third-party logger you cannot change
const vendorLogger = {
  lines: [],
  write(level, message, meta = {}) {
    this.lines.push(`${level.toUpperCase()} ${message} ${JSON.stringify(meta)}`);
  },
};

// The interface your application expects
export function makeLogger(vendor) {
  return {
    info: (message, meta) => vendor.write("info", message, meta),
    error: (message, error) => vendor.write("error", message, { error: error?.message }),
  };
}

const logger = makeLogger(vendorLogger);
logger.info("order placed", { id: "o-1" });
logger.error("charge failed", new Error("card declined"));
console.log(vendorLogger.lines);
Text
[
  'INFO order placed {"id":"o-1"}',
  'ERROR charge failed {"error":"card declined"}'
]

Application code calls logger.info and logger.error, so replacing the vendor means writing a new makeLogger, not editing every call. The adapter also lets you decide what an error call means in the vendor's terms, here by extracting the message. In tests you can pass any object with a write method, which gives you a fake without mocking modules.

Adapting a callback API to promises

A very common adapter wraps an old callback-style function. Node.js provides util.promisify for the standard error-first convention.

promisify.mjsJavaScript
import { promisify } from "node:util";

function legacyLookup(id, callback) {
  setTimeout(() => {
    if (id === 0) return callback(new Error("not found"));
    callback(null, { id, name: "Ada" });
  }, 1);
}

const lookup = promisify(legacyLookup);

console.log(await lookup(1));
try {
  await lookup(0);
} catch (err) {
  console.log(err.message);
}
Text
{ id: 1, name: 'Ada' }
not found

promisify is an adapter from the callback interface to the promise interface. For callbacks that do not follow the error-first convention, you write the adapter by hand.

manual-promise.mjsJavaScript
function onceReady(emitterLike, callback) {
  setTimeout(() => callback({ ok: true }), 1);
}

const ready = () => new Promise((resolve) => onceReady({}, resolve));
console.log(await ready());
Text
{ ok: true }

A class-based adapter

When the adapted object has state or several methods, a class makes the adapter explicit. This one makes a Redis-like client and a Map look like the same cache.

cache-adapters.mjsJavaScript
export class MemoryCache {
  #store = new Map();
  async get(key) {
    return this.#store.get(key) ?? null;
  }
  async set(key, value) {
    this.#store.set(key, value);
  }
}

// Adapts a client with get(key, cb) and setex(key, seconds, value, cb)
export class CallbackClientCache {
  constructor(client, ttlSeconds = 60) {
    this.client = client;
    this.ttlSeconds = ttlSeconds;
  }
  get(key) {
    return new Promise((resolve, reject) =>
      this.client.get(key, (err, value) => (err ? reject(err) : resolve(value ?? null))),
    );
  }
  set(key, value) {
    return new Promise((resolve, reject) =>
      this.client.setex(key, this.ttlSeconds, value, (err) => (err ? reject(err) : resolve())),
    );
  }
}

const fakeClient = {
  data: {},
  get(key, cb) {
    cb(null, this.data[key]);
  },
  setex(key, ttl, value, cb) {
    this.data[key] = value;
    cb(null);
  },
};

for (const cache of [new MemoryCache(), new CallbackClientCache(fakeClient)]) {
  await cache.set("greeting", "hello");
  console.log(cache.constructor.name, await cache.get("greeting"), await cache.get("missing"));
}
Text
MemoryCache hello null
CallbackClientCache hello null

Both classes present get and set returning promises, and a miss is null in both. The caller does not know which cache it has. This is the shape used when you want to run an in-memory cache in tests and a real server in production, and the adapter is what lets one Cache interface cover both. It overlaps with the bridge pattern, the difference being intent: an adapter fixes an existing mismatch after the fact, while a bridge is designed up front.

Adapting in TypeScript

Types make the target interface explicit, and the compiler verifies the adapter.

adapter.tsTypeScript
interface Clock {
  now(): Date;
}

// A library with a different shape
const vendorTime = { currentTimestampMs: () => 1_700_000_000_000 };

class VendorClockAdapter implements Clock {
  constructor(private readonly vendor: { currentTimestampMs(): number }) {}
  now(): Date {
    return new Date(this.vendor.currentTimestampMs());
  }
}

const clock: Clock = new VendorClockAdapter(vendorTime);
console.log(clock.now().toISOString());
Text
2023-11-14T22:13:20.000Z

If Clock later gains a method, the compiler flags the adapter until you implement it. The fixed timestamp makes the output deterministic.

Testing an adapter

An adapter is a pure mapping in most cases, so tests are table-driven: input shape in, output shape out, including the odd inputs you meet in production.

adapter.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { fromProvider } from "./payment-adapter.mjs";

test("maps a settled payment", () => {
  assert.deepEqual(
    fromProvider({ payment_id: "p1", amount: "5.00", currency_code: "eur", state: "SETTLED" }),
    { id: "p1", amountCents: 500, currency: "EUR", status: "paid" },
  );
});

test("treats an unknown state as unknown, not a crash", () => {
  assert.equal(fromProvider({ payment_id: "p2", amount: "1", currency_code: "usd", state: "REVIEW" }).status, "unknown");
});
Text
✔ maps a settled payment (0.9ms)
✔ treats an unknown state as unknown, not a crash (0.2ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

Keep a few real captured responses from the provider as fixtures, because the shape documentation is often incomplete, and the adapter's edge cases come from real data. When the provider's contract changes, these tests fail where the change is, and nowhere else.

Adapter versus facade versus decorator

Three wrappers are easy to mix up. An adapter changes the interface to match what the client expects. A facade keeps its own new, simpler interface over a complex subsystem. A decorator keeps the interface the same and adds behavior. If the wrapper's job is translation, it is an adapter.

Pitfalls

  • Leaky adapters. If the adapter returns the vendor's objects, or passes vendor errors upward, the vendor's types leak into your code. Convert results and errors at the boundary.

  • Lossy mapping. Converting "19.99" through floating-point can produce 1998.9999999999998 before rounding, which is why the adapter rounds. Decide what to do with fields you do not map, and whether to keep the raw payload for debugging.

  • Adapter sprawl. One adapter per provider is right. One adapter per call site is a sign the interface is not agreed.

  • Over-adapting your own code. If you control both sides, change the interface. An adapter is for code you cannot or should not modify.

Where the advice stops

An adapter adds a layer, and every layer is a place a bug can hide and a name someone must learn. Use one where you consume a shape you do not own and want to isolate it, such as a vendor SDK, a legacy module or an external API. When both sides are yours and the mismatch is small, just fix the interface.

Where adapters live in a project

Put adapters at the edge of your system, next to the integration they wrap, and let the rest of the code import only your own interface. A layout such as integrations/payments/provider-a.js and integrations/payments/index.js, where the index exports a createPaymentGateway factory, keeps vendor names out of the domain. A lint rule that forbids importing a vendor SDK outside the integrations folder turns the convention into a guarantee. When the vendor is replaced, or a second provider is added for redundancy, the work is one new file that satisfies the same interface, plus a line that chooses between them.

It also pays to give the adapter the vocabulary of your domain and not the vendor's. If your business says "refund" and the vendor says "reversal", the adapter's method is refund. Readers of your code should never have to learn the vendor's words, and the translation table sits in one reviewed place. Over time this documentation value is as useful as the decoupling: the adapter shows exactly which parts of the vendor's API your product depends on.

Handling versions and errors

Vendors version their APIs, and an adapter is where you absorb it. If provider API version two renames a field, the adapter reads both names for a while and emits one shape. Errors deserve the same treatment: map the vendor's error codes into a small set of your own, such as declined, unavailable and invalid, so callers decide what to do without parsing vendor strings. Keep the original error attached as a cause, using the cause option of Error, so logs retain the detail while the interface stays clean.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

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