Skip to Content
Mengty Learns
Design

Adapter Pattern

Wrap incompatible third-party or legacy interfaces behind a single contract your application already expects.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

1. Intent

TL;DR

Convert the interface of an existing or third-party class into another interface that your application code expects, letting incompatible components collaborate without rewriting either one.

2. Problem

Suppose your backup service stores database snapshots in AWS S3. Later, your team adds multi-cloud support for Google Cloud Storage (GCS) or a local MinIO-compatible mock.

The AWS SDK expects s3.send(new PutObjectCommand({ Bucket, Key, Body })) and returns { ETag }, while the GCS SDK expects bucket.file(key).save(buffer) and returns void. If your backup service branches on provider types everywhere, cloud SDK details leak straight into your domain logic.

Without an Adapter, BackupService must know each cloud SDK's incompatible API.

3. Solution

Define a single Target interface (BlobStore) owned by your application with clean methods like putObject(key, data) and getObject(key).

Then write one Adapter class per third-party SDK (S3BlobAdapter, GcsBlobAdapter). Each adapter implements BlobStore, holds a reference to its vendor SDK client, translates incoming arguments into the SDK's expected format, and normalizes the SDK's return value back into your domain type.

4. Real-world analogy

5. Flow: watch it work

Adapter Pattern: Client → Adapter → SDK

Overview of Adapter Pattern: Client → Adapter → SDK. 6 steps.
Overview6 steps in this flow

Press Start or tap any step dot to trace the path.

▸All steps (6)

6. Structure

Object Adapter uses composition: the adapter implements Target and wraps the Adaptee.

7. Code

// Target interface owned by our application
interface BlobReceipt {
  key: string;
  etag: string;
}

interface BlobStore {
  putObject(key: string, data: Uint8Array): Promise<BlobReceipt>;
  getObject(key: string): Promise<Uint8Array | null>;
}

// Incompatible third-party SDK #1 (AWS-style command pattern)
class AwsS3Sdk {
  private readonly objects = new Map<string, Uint8Array>();

  async send(command: { type: 'put' | 'get'; Bucket: string; Key: string; Body?: Uint8Array }) {
    const path = `${command.Bucket}/${command.Key}`;
    if (command.type === 'put' && command.Body) {
      this.objects.set(path, command.Body);
      return { ETag: `"s3-${command.Body.byteLength}"` };
    }
    return { Body: this.objects.get(path) ?? null };
  }
}

// Incompatible third-party SDK #2 (GCS-style fluent file handle)
class GcsSdk {
  private readonly files = new Map<string, Uint8Array>();

  bucket(name: string) {
    return {
      file: (key: string) => ({
        save: async (buf: Uint8Array) => {
          this.files.set(`${name}/${key}`, buf);
        },
        download: async (): Promise<[Uint8Array] | null> => {
          const data = this.files.get(`${name}/${key}`);
          return data ? [data] : null;
        },
      }),
    };
  }
}

// Adapter 1: AWS S3 -> BlobStore
class S3BlobAdapter implements BlobStore {
  constructor(
    private readonly sdk: AwsS3Sdk,
    private readonly bucketName: string,
  ) {}

  async putObject(key: string, data: Uint8Array): Promise<BlobReceipt> {
    const res = await this.sdk.send({
      type: 'put',
      Bucket: this.bucketName,
      Key: key,
      Body: data,
    });
    return { key, etag: res.ETag ?? 'unknown' };
  }

  async getObject(key: string): Promise<Uint8Array | null> {
    const res = await this.sdk.send({ type: 'get', Bucket: this.bucketName, Key: key });
    return res.Body ?? null;
  }
}

// Adapter 2: GCS -> BlobStore
class GcsBlobAdapter implements BlobStore {
  constructor(
    private readonly sdk: GcsSdk,
    private readonly bucketName: string,
  ) {}

  async putObject(key: string, data: Uint8Array): Promise<BlobReceipt> {
    await this.sdk.bucket(this.bucketName).file(key).save(data);
    return { key, etag: `gcs-${data.byteLength}` };
  }

  async getObject(key: string): Promise<Uint8Array | null> {
    const result = await this.sdk.bucket(this.bucketName).file(key).download();
    return result ? result[0] : null;
  }
}

// Client works identically with either cloud
async function archiveSnapshot(store: BlobStore, key: string, payload: Uint8Array) {
  return store.putObject(key, payload);
}

const s3Store = new S3BlobAdapter(new AwsS3Sdk(), 'prod-backups');
const gcsStore = new GcsBlobAdapter(new GcsSdk(), 'dr-backups');

await archiveSnapshot(s3Store, 'db-2026-11-26.bin', new Uint8Array([1, 2, 3]));
await archiveSnapshot(gcsStore, 'db-2026-11-26.bin', new Uint8Array([1, 2, 3]));

8. When to use / when to avoid

When to use
  • You must integrate a third-party SDK, legacy module, or external API whose signature does not match your domain contract.
  • You want to support multiple vendors (S3, GCS, local disk) behind one stable application interface.
  • You want to isolate vendor-specific error shapes and DTOs so they do not leak across your codebase.
When to avoid
  • You own both the caller and the callee—simply refactor the callee method signature directly.
  • The adapter has to invent missing data or fake unsupported semantics that break the Target contract.
  • You are wrapping a tiny one-off utility function where a single helper function is clearer.

When NOT to use it

Overengineering happens when teams write FooAdapter wrappers around internal modules they control, just to follow a pattern. If you can edit the source class directly without breaking external consumers, changing its interface is cleaner than maintaining an extra translation layer.

Real-world example in this stack

In lib/source.ts, this site adapts Fumadocs' docs.toFumadocsSource() output—filtering out status: 'draft' pages in production builds—into the source shape expected by Fumadocs loader(). Likewise, in Hexagonal Architecture, every driven database or HTTP adapter translates between a domain port and an external driver.

9. How to implement

Identify the Target interface and the Adaptee

Define the minimal interface your application wants to call (BlobStore), and inspect the incompatible external API (AwsS3Sdk).

Create the Adapter class

Have the adapter implements BlobStore and accept the Adaptee instance via its constructor.

Translate calls and normalize responses

Map parameters, convert exceptions or error codes into domain errors, and return the Target's data types.

Wire the Adapter at the composition root

Inject S3BlobAdapter or GcsBlobAdapter at startup so business logic only imports BlobStore.

10. Pros / Cons

Pros
  • Single Responsibility Principle: keeps data translation out of business logic.
  • Open/Closed Principle: add new vendor adapters without editing client code.
  • Makes testing easy by swapping in an in-memory implementation of the Target interface.
Cons
  • Adds extra classes and indirection when a direct refactor would have been simpler.
  • Leaky abstractions happen if two wrapped SDKs have fundamentally different semantics (e.g. eventual vs strong consistency).

11. Relations

Adapter vs Bridge

Adapter wraps incompatible existing interfaces after the fact; Bridge is designed up front to separate two independent hierarchies.

Adapter vs Decorator

Adapter changes the interface of a wrapped object; Decorator keeps the exact same interface and adds behavior around it.

Adapter vs Facade

Adapter wraps one incompatible object to match an expected interface; Facade creates a brand-new simplified interface over an entire subsystem.

12. Check yourself

Check Yourself

1. How does an Object Adapter connect the Client's Target interface to an incompatible third-party SDK?

2. When is writing an Adapter usually unnecessary?

Sources