Skip to content
03 / AdapterStructural15 minTypeScript

Two couriers. One tracking interface.

Wrap incompatible shipping-provider responses behind one interface, validate external data, and keep the tracking UI unchanged.

Jump to the working demo

Start with the real-world problem

Your tracking screen uses ParcelWire. A second courier, SwiftShip, returns different field names and status values. You want to add the new courier without teaching every screen, notification, and report about its response format.

Before the pattern

Every consumer checks which courier produced the response, then translates numeric codes or nested strings. A provider schema change forces edits across the application.

What Adapter changes

An adapter translates an existing interface into the one your application expects. Each provider gets its own wrapper. The client depends only on TrackingProvider and receives the same TrackingStatus shape from either adapter.

Client contract

TrackingProvider

Exposes lookup() returning a normalized tracking ID and status.

Adapters

ParcelWireAdapter · SwiftShipAdapter

Validate captured responses and translate provider-specific fields.

Existing interfaces

Numeric state · Nested status

The fictional courier payloads remain unchanged outside their wrappers.

  1. 01

    Define your application's vocabulary

    TrackingStatus uses in_transit and delivered. The trackingLabel client formats those two values and knows nothing about numeric codes or nested provider fields.

  2. 02

    Translate at one boundary

    ParcelWire uses tracking_code and state 20 or 90. SwiftShip uses id and delivery.status moving or arrived. Both map to the same output. Switch providers in the demo: the normalized result stays consistent.

  3. 03

    Reject what you cannot interpret

    The input type is unknown because an external response is not made trustworthy by a TypeScript assertion. The adapters check its shape, ID, and status. Unsupported statuses throw instead of quietly pretending the parcel was delivered.

Try it in the workbench

Live · runs in your browser

Provider response

{
  "tracking_code": "PKG-204",
  "state": 90
}

Result

Normalize the response, then switch providers. The payload changes; your tracking interface does not.

Fictional courier fixtures. No external API calls.

The complete implementation

Download this self-contained example. With Node.js installed, run npx tsx adapter.ts in the download directory. The first run may install the TypeScript runner. No API credentials or other project files are needed.

adapter.ts
Download
export type TrackingStatus = { id: string; status: 'in_transit' | 'delivered' }
export interface TrackingProvider { lookup(): TrackingStatus }

function record(value: unknown): Record<string, unknown> {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    throw new Error('Expected a provider response object.')
  }
  return value as Record<string, unknown>
}

function trackingId(value: unknown): string {
  if (typeof value !== 'string' || !value.trim()) {
    throw new Error('Provider response is missing a tracking ID.')
  }
  return value.trim()
}

// Fictional providers. The constructor receives a captured API response.
export class ParcelWireAdapter implements TrackingProvider {
  private response: unknown
  constructor(response: unknown) { this.response = response }
  lookup(): TrackingStatus {
    const data = record(this.response)
    const id = trackingId(data.tracking_code)
    if (data.state === 20) return { id, status: 'in_transit' }
    if (data.state === 90) return { id, status: 'delivered' }
    throw new Error('ParcelWire returned an unsupported status.')
  }
}

export class SwiftShipAdapter implements TrackingProvider {
  private response: unknown
  constructor(response: unknown) { this.response = response }
  lookup(): TrackingStatus {
    const data = record(this.response)
    const id = trackingId(data.id)
    const delivery = record(data.delivery)
    if (delivery.status === 'moving') return { id, status: 'in_transit' }
    if (delivery.status === 'arrived') return { id, status: 'delivered' }
    throw new Error('SwiftShip returned an unsupported status.')
  }
}

// This client has no knowledge of either provider's response format.
export function trackingLabel(provider: TrackingProvider) {
  const shipment = provider.lookup()
  return `${shipment.id}: ${shipment.status === 'delivered' ? 'Delivered' : 'On the way'}`
}

// Run this example with: npx tsx adapter.ts
const parcelWire = new ParcelWireAdapter({ tracking_code: 'PKG-204', state: 90 })
const swiftShip = new SwiftShipAdapter({ id: 'PKG-204', delivery: { status: 'arrived' } })
console.log(trackingLabel(parcelWire))
console.log(trackingLabel(swiftShip))

Expected terminal output

PKG-204: Delivered
PKG-204: Delivered

Make the tradeoff deliberately

A good fit

  • An existing library or provider has an interface you cannot change.
  • Several integrations must satisfy one application-level contract.

Keep it simpler when

  • You own both interfaces and can simplify them directly.
  • You are choosing interchangeable algorithms rather than translating an interface; consider Strategy instead.

Taking this into a real system

These providers and payloads are fictional fixtures. No network request is sent. A real adapter also needs authenticated transport, timeouts, rate-limit handling, schema-version checks, and fixtures captured from the provider's documented API. Keep raw data out of logs when it contains personal information. Decide explicitly whether unknown statuses should fail, be quarantined, or map to a separate unknown state.

Your turn

Make one small extension

Add a third provider returning { shipment: 'PKG-204', complete: true }. Can trackingLabel remain unchanged?

Show the reasoning

Yes. Implement TrackingProvider, validate shipment and complete, and map true to delivered and false to in_transit. Then pass the new adapter to trackingLabel. If you have to add a provider branch inside trackingLabel, the translation boundary is leaking.

Further reading

Examples are original teaching implementations. Reference links provide language and API context; they are not claims that a provider uses this exact implementation.