Pattern 08/22 · Structural

Adapter

Insert a translation layer at the boundary: it takes data and calls in someone else's shape (a third-party API, a legacy module, a DTO) and returns exactly your internal contract, so the core of the system only ever knows its own data types.

Structural●●○13 min read8 stepsalso known as: Wrapper, Translator, Anti-Corruption Layer (the module-scale version)
adapterdtoapilegacyanti-corruption layersnake caserefactor

01 — It starts with code that is breaking

Problem

A shop's admin panel. The order list page: const { data } = await useFetch("/legacy/orders"), and then in the template people write order.created_at, order.line_items[i].unit_price. data is any — $fetch knows nothing about the schema — so TypeScript sits on the sidelines. The unit_price the backend returns is a string "199000" in cents, because back in 2019 someone copied it straight from a database column.

Then a teammate wants the price including VAT: order.unit_price * 1.1. JS sees a string and silently coerces it to a number, gets 218900, and the template prints "218900 VND". The number is arithmetically right, off by 100x in units, and not a single tool complains. That is the kind of bug that only surfaces in the end-of-month statement.

The backend ships v2: created_at becomes createdAt, line_items becomes items. You grep 47 hits across 19 files, fix 44, and the other 3 are in templates — where any used to shelter them, now nobody finds them. Three blank pages, and that week's merge has to be reverted. Root cause: someone else's JSON shape is playing the role of your system's data types, so every change on their side becomes a refactor on yours.

Payments too. You call stripe.paymentIntent(...) directly in the checkout component, then pass client_secret down as a prop to the "Pay" button. Now product switches to another vendor: you have to change the UI, and that component cannot be tested because every render is a network call. Meanwhile there is an old callback-style util lib getThing(id, cb) that you are not allowed to modify (3 other teams use it), so every call site writes its own promise wrapper — 5 variants, each handling errors differently.

Step back and look: knowledge of data shapes is scattered everywhere. Nobody can answer "what is an Order in this system?" — the real answer is "whatever the API returns today". And because the boundary has no gate, any creeps all the way into the domain, vendor mutations become mutations in Vue state, and refactoring is an archaeological dig.

02 — The idea, before touching code

Solution

An Adapter is a component that implements your internal contract but, inside, calls an API with a different shape. Three roles: Target is the contract your code wants to use (Order, PaymentGateway), Adaptee is what already exists (the v1 endpoint, a callback lib, a vendor SDK), Adapter is where the two get translated. Iron rule: the Adaptee's shape may only exist in one file — the adapter file.

There are two directions. Inbound (toDomain(dto) / mapResponse) for the read path, and in TS it is also a gate: the one place where unknown gets checked and narrowed into a domain type, so past the boundary everything has real types. Outbound (toApi(domain) / mapRequest) for the write path, because POST/PATCH also need the right field names, the right units, and must not carry internal fields.

The cost is real: one more file per boundary, one more mapping table to keep in sync. It is worth it when the shape is not yours to decide (someone else's API, a legacy lib, already-stored data), when you need a second implementation (a fake for tests, a second vendor), or when two systems have to coexist during a migration. If there is only one shape and it already is your contract, Adapter is a tax — read the pitfalls before writing one.

03 — Doing it for real, one code fragment per step

Step by step

1

Draw the boundary: where does other people's data come in

Before writing anything, list every point where foreign data enters: $fetch/useFetch to an API, vendor SDKs (payment, SMS, maps), message queue consumers, CSV/Excel imports, localStorage/IndexedDB, and legacy libs you cannot modify. Each point is a potential adapter — or a place to leave alone, if its shape already is your contract.

Here is a typical "before" version. Notice how many places have to know the endpoint's details: snake_case names, prices in cents, dates as strings, and an items loop the domain does not care about.

tsOrderList.vue (before)
const { data } = await useFetch("/legacy/orders")   // data: any

// XXX: data: any -> no tooling knows what the real payload looks like
// XXX: four pieces of "endpoint knowledge" are living right in the rendering code:
//   order.created_at                       <- THEIR name, not ours
//   order.line_items[i].unit_price         <- the string "199000", in cents
//   order.customer.full_name
//   (order.vat_rate * order.unit_price)    <- JS silently coerces string -> number

// XXX: this line runs "correctly", and is still off by 100x:
const total = data.value?.orders
  .flatMap(o => o.line_items)
  .reduce((s, li) => s + li.unit_price * 1.1, 0)     // 199000 * 1.1 = 218900 "VND"
Four pieces of endpoint knowledge inside rendering code. Change the endpoint = change the rendering code.
Key pointIf the UI knows the API's field names, the UI is already part of that API. Adapter exists to cut that cord.
2

Define the internal contract before writing a single line of translation

Describe the domain in your language, not in their columns. Money (VND, integer), publishedAt (a date type, or an ISO string on purpose), authorName rather than author_name. The unit belongs in the type name, because that is exactly what the "100x" bug steals.

Writing this type first turns every later mapping into a closed problem: "I have a LegacyOrderDto, I need an Order, I am allowed to throw if the data is insufficient". Without a target type, mapping is a job with no definition of done.

tsdomain/order.ts
/** VND, integer. The type name carries the unit: a "cents vs dong" bug has a harder time sneaking in. */
export type Money = number & { readonly __unit: "VND" }
export const vnd = (n: number): Money => n as Money

export interface OrderLine {
  readonly sku: string
  readonly qty: number
  readonly unitPrice: Money
}

export interface Order {
  readonly id: string
  readonly customerName: string
  readonly placedAt: Date
  readonly lines: OrderLine[]
  readonly status: "new" | "cancelled"
}
readonly + the unit in the type name: the internal contract should not just differ in naming, it should differ in quality from the DTO.
Key pointThe domain type describes your business. If it looks exactly like the partner's JSON (field names included), you do not have an internal contract yet — you are aliasing the DTO.
3

Inbound adapter: a gate from unknown down to the domain

A one-way adapter is a pure function: DTO in, domain out, throw when the data does not match the contract. Do not as Order: a cast checks nothing, it just silences the compiler and turns garbage data into an error three call levels later.

The most valuable part is not the authorName: d.author_name line — it is the blocking part: unknown → check → domain. This is the only place in the system where you are allowed to trust someone else's field name.

tsapi/legacy-order-mapper.ts
import type { Order, OrderLine } from "~/domain/order"

/** THEIR shape: only this file is allowed to know it exists. */
interface LegacyOrderDto {
  id: number
  created_at: string
  customer?: { full_name?: string }
  line_items?: Array<{ sku: string, qty: number, unit_price: string }>
  state?: string
}

const isDto = (x: unknown): x is LegacyOrderDto =>
  typeof x === "object" && x !== null
  && typeof (x as LegacyOrderDto).id === "number"
  && typeof (x as LegacyOrderDto).created_at === "string"

export function toDomain(raw: unknown): Order {
  if (!isDto(raw)) throw new Error("payload does not match LegacyOrderDto")

  const lines: OrderLine[] = (raw.line_items ?? []).map(li => ({
    sku: li.sku,
    qty: Number(li.qty),
    unitPrice: Number(li.unit_price) as OrderLine["unitPrice"], // cents -> VND: EXPLICIT, in one place
  }))

  return {
    id: String(raw.id),
    customerName: raw.customer?.full_name ?? "(walk-in customer)",
    placedAt: new Date(raw.created_at),
    lines,
    status: raw.state === "cnl" ? "cancelled" : "new",
  }
}
Whether unit_price is cents or VND is now a question for exactly one line. Nobody in the UI has to guess anymore.
Key pointThe inbound adapter is where any goes to die. Past it, no file casts, no file reads snake_case.
4

Outbound adapter: translate back, and send only what they need

The write path is the one most often forgotten. You POST a whole domain object, the backend shrugs because it does not understand placedAt, and the data the user just entered silently disappears. toApi returns exactly the list of fields the endpoint needs, in the right format, in the right units.

This direction is also where you block over-posting: internal fields (status set by an admin, internalNote, marginVnd) must not drift out to the vendor. One line of exclusion in the adapter is far cheaper than an incident.

tsapi/legacy-order-mapper.ts (continued)
/** Domain -> DTO. No internal fields leaked, their date format exactly. */
export function toApi(o: Order): LegacyOrderDto {
  return {
    id: Number(o.id),
    created_at: o.placedAt.toISOString().slice(0, 19).replace("T", " "), // "yyyy-MM-dd HH:mm:ss"
    customer: { full_name: o.customerName },
    line_items: o.lines.map(li => ({
      sku: li.sku,
      qty: String(li.qty),
      unit_price: String(li.unitPrice),   // VND -> cents: the INVERSE of toDomain
    })),
    // state: NOT sent. Status is the backend's call, not the client's.
  }
}

/** PATCH: send only what changed, still through the same translation contract. */
export const toApiPatch = (patch: Partial<Order>) => toApi({ ...defaults, ...patch })
Two functions side by side, in the same file: with cents → VND and VND → cents next to each other, any mismatch jumps out.
Key pointA two-way adapter keeps the domain clean on both reads and writes. A one-way adapter only solves half the problem, and usually the easy half.
5

Put the adapter in the API layer, not in the component

The adapter lives where the API is called — api/orders.ts, server/api/*, a repository — and is exported as functions typed with the domain. The component only sees listOrders(): Promise<Order[]>. This is a boundary you can enforce with tooling: ESLint no-restricted-imports blocks useFetch in components/, and the domain may not import from api/.

Without a file boundary, an adapter is just advice. And advice loses to deadlines.

tsapi/orders.ts
import { toDomain } from "./legacy-order-mapper"

interface ListResponse { orders: unknown[] }

/** Internal contract: the caller gets Order, never unknown. */
export async function listOrders(): Promise<Order[]> {
  const res = await $fetch<ListResponse>("/legacy/orders")
  return res.orders.map(toDomain)     // gate: 1 line, every data error funnels here
}

export async function createOrder(o: Order): Promise<void> {
  await $fetch("/legacy/orders", { method: "POST", body: toApi(o) })
}

// OrderList.vue: const { data } = await useAsyncData("orders", listOrders)
// -> data: Order[] | undefined, correct autocomplete, no more "any" in the template
The component no longer holds any knowledge of the endpoint. API v2 lands: change api/orders.ts, not the UI.
Key pointAn adapter is only trustworthy when it sits on a module boundary that lint/types can guard. Adapters scattered through .vue files get copied 19 times.
6

A class-based adapter when there is more than one implementation

When you need to pick the vendor at runtime (Stripe today, vendor B next month) or a fake for tests, promote it to an interface. The interface is the Target in GoF terms; each vendor gets its own adapter class, the constructor takes credentials/config, the methods translate to their SDK. This is exactly where Singleton + DI fit in: the vendor adapter is a dependency injected into the service.

A class is not a requirement of the pattern — it is a consequence of having state (apiKey, timeout, an initialized client) and several methods that need translating together.

tspayment/payment-gateway.ts
export interface PaymentGateway {
  createIntent(amount: Money, currency: "VND"): Promise<{ intentId: string, clientSecret: string }>
  capture(intentId: string, amount: Money): Promise<"succeeded" | "failed">
}

/** Adaptee = Stripe SDK. The SDK's type names DO NOT leave this file. */
export class StripeAdapter implements PaymentGateway {
  constructor(private readonly stripe: Stripe, private readonly webhookSecret: string) {}

  createIntent(amount, currency) {
    return this.stripe.paymentIntents.create({
      amount: amount * 100,          // VND -> minor unit: the ONLY place units get translated
      currency,
    }).then(i => ({ intentId: i.id, clientSecret: i.client_secret ?? "" }))
  }

  capture(intentId, amount) {
    return this.stripe.paymentIntents.capture(intentId)
      .then(() => "succeeded", () => "failed")
  }
}

// Test / dev: same contract, no network
export class FakeGateway implements PaymentGateway {
  private n = 0
  createIntent: PaymentGateway["createIntent"] = async () => ({ intentId: "pi_" + ++this.n, clientSecret: "secret" })
  capture: PaymentGateway["capture"] = async () => "succeeded"
}
FakeGateway is an adapter for tests, with the same contract. The UI does not change a line when you switch vendors.
Key pointInterface + adapter turns "switch providers" from a 20-file refactor into one new file and one line of wiring.
7

Round-trip test: toApi ∘ toDomain must not lose data

The classic failure mode of a two-way adapter: someone adds a field to toDomain and forgets toApi. Reads have everything, writes silently lose it. The cheapest test that catches exactly this bug is a round trip: real DTO → domain → DTO, then compare against a declared allowlist.

Take the fixture from a real payload (copied from the network tab, or a snapshot of a staging response), do not type it by hand — typing it by hand means testing your own imagination. Fields that intentionally do not round-trip (server-generated, read-only) must be listed explicitly, so every newly lost field has to be explained.

tslegacy-order-mapper.test.ts
// Fixture: copy a REAL payload from the network tab, do not type it from memory
const fixture = {
  id: 7,
  created_at: "2024-03-07 14:20:00",
  customer: { full_name: "Ms. A" },
  line_items: [{ sku: "A1", qty: "2", unit_price: "199000" }],
  state: "new",
  profit_margin: 0.31,
  updated_at: "2024-03-08 09:00:00",
}

// toDomain: everyone remembers it. toApi: often FORGOTTEN when a field is added.
const toDomain = (d: typeof fixture) => ({
  id: String(d.id),
  customerName: d.customer.full_name,
  lines: d.line_items.map(li => ({ sku: li.sku, qty: Number(li.qty), unitPrice: Number(li.unit_price) })),
})
const toApi = (o: ReturnType<typeof toDomain>) => ({
  id: Number(o.id),
  customer: { full_name: o.customerName },
  line_items: o.lines.map(li => ({ sku: li.sku, qty: String(li.qty) })), // unit_price FORGOTTEN
})

// Fields that intentionally do not come back (server-generated): declare them here, any other field fails
const readOnly = new Set(["state", "updated_at", "profit_margin"])
const again = toApi(toDomain(fixture))
const lost = Object.keys(fixture)
  .filter(k => !readOnly.has(k) && JSON.stringify((fixture as any)[k]) !== JSON.stringify((again as any)[k]))

console.log("lost at order level:", lost.length ? lost.join(",") : "none")
console.log("lost at line_item:", Object.keys(fixture.line_items[0]).filter(k => !(k in (again.line_items[0] as object))).join(","))
console
lost at order level: created_at,line_items
lost at line_item: unit_price
This test fails on purpose: it points at exactly the two mismatches. In the repo it stays green and flags the moment someone adds a field to toDomain and forgets toApi.
Key pointAn adapter is a boundary, and a boundary test written once pays off forever. Testing the domain behind an adapter without testing the adapter is testing on assumptions.
8

Know when to stop: when an adapter is just a useless layer

An empty adapter is an anti-pattern. This is the most common form — an "api" file that just does return await $fetch(...) and names the result Order via a cast. It translates nothing, it only creates an illusion of safety: the type says Order, the real data is still the DTO, and now you can no longer find the boundary to fix.

Do not write an adapter when: there is only one implementation and you do not expect a second; the API's shape already is the contract you want; and no transformation is needed (no units, no defaults, no validation). In that case an interface OrderDto exported from an api/ file is enough. An adapter earns its keep when there is something to translate or a second implementation.

tsapi/empty-adapter.ts
// ✗ An "adapter" that translates nothing: just a cast, and a typed LIE
export async function listOrders(): Promise<Order[]> {
  const res = await $fetch("/legacy/orders")
  return res.orders as Order[]      // a snake_case DTO wearing an Order costume
}

// ✓ Honest: one shape, one type, no transformation -> no adapter needed
export interface OrderDto { id: number, created_at: string, line_items: LineItemDto[] }
export const listOrdersRaw = () => $fetch<ListResponse>("/legacy/orders")

// ✓ A real adapter when you have AT LEAST one of three: multiple vendors, a transformation
//   (unit/default/format), or a need to gate data coming in as unknown.
An adapter file without a single mapping line should be deleted, not "reused".
Key pointAn adapter exists because there is a mismatch. No mismatch means pure indirection, and pure indirection is a code-reading cost for everyone who comes after.

04 — Who talks to whom

Structure

  • TargetThe internal contract your code wants to use: the `Order` type, the `PaymentGateway` interface. You name it, you own it.
  • AdapteeWhat already exists and cannot be changed: the v1 endpoint, a vendor SDK, a callback lib, an imported file. Its shape is **not yours to decide**.
  • AdapterThe translation point: `toDomain`/`toApi` for data, or method calls for services. The **only** file allowed to know both worlds.
  • ClientDomain/service/component. Only sees the Target, never imports DTOs, does not know which vendor is behind it.
  • Fixture/Golden testA real payload + a round-trip test, keeping the adapter in line with the partner's contract when the partner changes it.
   ┌───────────────────────────────┐        ┌──────────────────────────────┐
   │ DOMAIN (Target)               │        │ ADAPTEE (their shape)        │
   │  Order, OrderLine, Money      │        │  { created_at, unit_price,   │
   │  PaymentGateway               │        │    line_items[], state }     │
   └───────────────▲───────────────┘        └───────────────▲──────────────┘
                   │ YOUR types                             │ THEIR types
                   │                                        │
        ┌──────────┴────────────────────────────────────────┴───────────┐
        │ ADAPTER  (api/legacy-order-mapper.ts)   ← the ONLY file       │
        │   toDomain(raw: unknown): Order    + gate, defaults, units    │
        │   toApi(o: Order): LegacyOrderDto  + format, drop internals   │
        └──────────────────────────┬────────────────────────────────────┘
                                   │ listOrders(): Promise<Order[]>
                                   ▼
                    ┌───────────────────────────────┐
                    │ CLIENT: service / component   │
                    │  no snake_case, no cents,     │
                    │  no "any"                     │
                    └───────────────────────────────┘

   A second vendor? Add a new adapter for the same Target. Client: 0 lines.

05 — Edit freely, run it right here

Try it: the same domain code, two adapters from two different worlds

tsdemo.ts
type Article = {
  id: number, title: string, authorName: string, viewCount: number, publishedAt: string
}

interface LegacyDto {
  id: number
  title: string
  author_name: string
  view_count: number
  created_at: string
}
interface VendorDto {
  articleId: string
  fields: { name: string, reads: number, author: { display: string }, published: string }
}

// Adapter 1: old CMS, snake_case + "yyyy-MM-dd HH:mm:ss" — translates BOTH ways
const legacyAdapter = {
  toDomain: (d: LegacyDto): Article => ({
    id: d.id, title: d.title, authorName: d.author_name, viewCount: d.view_count,
    publishedAt: d.created_at.replace(' ', 'T') + 'Z',
  }),
  toApi: (a: Article): LegacyDto => ({
    id: a.id, title: a.title, author_name: a.authorName, view_count: a.viewCount,
    created_at: a.publishedAt.slice(0, 10) + ' ' + a.publishedAt.slice(11, 19),
  }),
}

// Adapter 2: another vendor, a completely different shape -> domain code does not change a line
const vendorAdapter = {
  toDomain: (d: VendorDto): Article => ({
    id: Number(d.articleId.slice(2)), title: d.fields.name, authorName: d.fields.author.display,
    viewCount: d.fields.reads, publishedAt: d.fields.published,
  }),
}

// Domain code: only sees Article, does not know DTOs exist
const headline = (a: Article) =>
  a.title + ' — ' + a.authorName + ' · ' + a.viewCount + ' · ' + a.publishedAt

const legacy: LegacyDto = {
  id: 7, title: 'What is an Adapter', author_name: 'alex',
  view_count: 1284, created_at: '2024-03-07 14:20:00',
}
const vendor: VendorDto = {
  articleId: 'ID7',
  fields: {
    name: 'What is an Adapter', reads: 1284,
    author: { display: 'alex' }, published: '2024-03-07T14:20:00Z',
  },
}

console.log('1 legacy   :', headline(legacyAdapter.toDomain(legacy)))
console.log('2 vendor   :', headline(vendorAdapter.toDomain(vendor)))
const back = legacyAdapter.toApi(legacyAdapter.toDomain(legacy))
console.log('3 roundtrip:', JSON.stringify(back) === JSON.stringify(legacy))
console.log('4 domain   :', Object.keys(legacyAdapter.toDomain(legacy)).join(','))
console
1 legacy   : What is an Adapter — alex · 1284 · 2024-03-07T14:20:00Z
2 vendor   : What is an Adapter — alex · 1284 · 2024-03-07T14:20:00Z
3 roundtrip: true
4 domain   : id,title,authorName,viewCount,publishedAt

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • A third-party API whose shape is not yours to decide: snake_case, dates as strings, money in minor units, a { data: { result } } envelope.
  • You need several implementations of the same contract: Stripe + vendor B, SMS + email, S3 + disk, or a fake gateway to test the UI without a network.
  • Living with legacy: callback-style libs, old services, another team's module that you are not allowed to modify — the adapter is where you put the white lie.
  • Migrating your own API: v1 still has consumers, v2 is already live. An adapter lets domain code stand still while the server changes shape.
  • Two worlds that differ in substance, not just naming: cents ↔ dong, state: "cnl" ↔ status: "cancelled", string ↔ Date. This is when the adapter both translates and protects the domain from garbage data.
  • The same logic has to run on platforms with different APIs: browser (fetch, File System Access) vs Node (fs), IndexedDB vs SQLite — one Target, two adapters.

Don't use it when

  • Empty adapters (a .ts file that only casts or passes through) are a useless layer and worse than nothing: they create the illusion of a boundary, so the next refactor cannot find the real place to fix. No mapping lines means delete the file, do not "reuse" it.
  • The mapping tax is real. A CRUD admin app where every endpoint has XxxDto + Xxx + toDomain + toApi is 4 artifacts per table, and nobody wins: the DTO is the domain. The affordable version: one type, one parse function at the boundary, split only when there is a real mismatch or a second implementation.
  • Two-way adapters drifting apart: toDomain gets updated, toApi does not → PATCH silently drops fields. Or the adapter leaks: a function returns Order & { raw: any }, or the domain keeps the snake_case field names — the contamination is still there, it just moved. A round-trip test is the only reliable cure.
  • Stuffing business logic into the adapter (computing discounts, inferring status, adding VAT) because "adapters have no logic". An adapter only rephrases, it does not decide. Once toDomain computes money, nobody reviews it like business logic anymore.
  • A global interceptor that converts snake↔camel for every response (an axios/ofetch interceptor) looks very cheap and is systematically wrong: it also converts keys inside free-form payloads (metadata: {"user_id": ...} becomes userId when you least expect it), makes the mapping impossible to grep, and when the API returns something off-convention you get a bug that only reproduces on production data.
  • Trusting the adapter without gating the data: res.data.map(toDomain) with an any-typed DTO means toDomain blocks nothing — right types, garbage at runtime. The gate lives in unknown + a type guard, not in the function signature.

07 — You have met it already, just not by name

In real code

util.promisify (Node)

An adapter in the truest sense, shipped with Node: it turns a (err, data) => ... callback API into a Promise. fs.readFile does not change, only its shape does. Similarly, stream.Readable.fromWeb() / Readable.toWeb() are the official adapters between Node streams and Web streams.

Vue/Nuxt: useFetch({ transform }) and ofetch instances

useFetch has a transform option — the natural place for toDomain right at the fetch boundary, and createFetch({ onRequest, onResponse }) lets you build a client with auth attached + envelope unwrapping. It is a deliberate adapter when the transform actually transforms; it is an empty adapter when you only rename variables.

Repository/ORM: Prisma model → entity

Prisma returns OrderGetPayload<...> with _count, nested relations, and dates as the driver gives them. TS codebases pull out a toOrder(row) function in the repository: the domain receives an entity, and the DB schema's shape stays behind in the repository file — the only place import { Prisma } appears.

zod / io-ts: a parser is a one-way adapter

OrderSchema.transform(...) both validates and maps: unknown in, domain type out, throw if wrong. This is the inbound adapter with the gate written as a schema instead of ifs, and it stops being correct when the API changes — because the gate is not built on your memory.

Vendor SDKs: axios vs fetch, Stripe vs vendor B

Most SDKs wrap XMLHttpRequest/fetch behind an easier contract — an adapter for function shape, not data. The same pattern at the business layer: the service takes a PaymentGateway, dev/test runs FakeGateway, production runs StripeAdapter.

08 — Try it yourself

Exercise

Your SMS vendor is switching from `SmsV1` (returns `{ message_id, status_code: "00" }`, phone numbers without the `+`) to `SmsV2` (returns `{ id: { provider: number, external: string }, state: 1 }`). Write an `SmsGateway` interface (Target) with `send(phone, text): Promise<{ id: string, ok: boolean }>` and two adapters `SmsV1Adapter`, `SmsV2Adapter`, then call the same `notify(gw, ...)` function with both.

Hints, open them one at a time:

  1. The Target must not contain any vendor's details: no status_code, no state, no nested objects. Write the SmsGateway interface first, the two adapters after.
  2. SmsV1 uses "00" for success; SmsV2 uses state === 1. Those two translation tables live inside the adapters, not in notify.
  3. The v2 ID is a nested object (id.provider + id.external) — the adapter must return one stable string, e.g. provider + ":" + external, and that decision needs a test.

A shared interface, one adapter per vendor that translates names and also semantics ("00"/state:1 → ok), and normalizes the ID into one format. notify only knows SmsGateway, so it runs unchanged for both.

tsexercise.ts
interface SmsResult { id: string, ok: boolean }
interface SmsGateway { send(phone: string, text: string): Promise<SmsResult> }

// ---- vendor 1 ----
interface V1Response { message_id: string, status_code: string }
const v1Send = async (phone: string, text: string): Promise<V1Response> =>
  ({ message_id: "m-7", status_code: text === "" ? "99" : "00" })

export const SmsV1Adapter = (): SmsGateway => ({
  send: async (phone, text) => {
    const r = await v1Send(phone, text)
    return { id: "1:" + r.message_id, ok: r.status_code === "00" }
  },
})

// ---- vendor 2 ----
interface V2Response { id: { provider: number, external: string }, state: number }
const v2Send = async (phone: string, text: string): Promise<V2Response> =>
  ({ id: { provider: 2, external: "m-7" }, state: text === "" ? 0 : 1 })

export const SmsV2Adapter = (): SmsGateway => ({
  send: async (phone, text) => {
    const r = await v2Send(phone, text)
    return { id: r.id.provider + ":" + r.id.external, ok: r.state === 1 }
  },
})

// ---- client: knows no vendor, no "00", no "state" ----
async function notify(gw: SmsGateway, phone: string, name: string) {
  const r = await gw.send(phone, "Hi " + name)
  return (r.ok ? "OK " : "FAIL ") + r.id
}

;(async () => {
  console.log(await notify(SmsV1Adapter(), "+8490123456", "Alex"))
  console.log(await notify(SmsV2Adapter(), "+8490123456", "Alex"))
  console.log(await notify(SmsV2Adapter(), "+8490123456", ""))
})()

09 — Read them in pairs to see the essence

Related patterns

  • FacadeBoth wrap something, but Facade **makes an API easier to use** (folding many calls into one function), while Adapter **makes an API fit an existing contract**. Facade does not need a Target; Adapter must have one.
  • BridgeBridge separates abstraction from implementation **up front** so both sides can evolve independently; Adapter connects two things that are already written, usually later. Bridge is design ahead of time, Adapter is a fix after the fact — the same composition mechanism.
  • ProxyProxy keeps **the same** contract as the object it stands in for (adding laziness, caching, permissions). Adapter **changes** the contract. One class can do both, but call it by what it actually does.
  • DecoratorDecorator adds behavior and returns exactly the same type (`withRetry(gw)` is still a `PaymentGateway`); Adapter returns a **different** type. This pair often nests: a vendor adapter, wrapped by a retry/log decorator.