Course contentsShow
← Node.js
Lesson 715 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Adapter Pattern for Service APIs

Uniformly access disparate third-party web services through a standardized adapter interface.

In this lesson, you will learn how to use the Adapter Pattern to wrap inconsistent third-party web services into a uniform interface, allowing your application to interact with them seamlessly.

The Problem: API Mismatch

As you build complex systems, you often integrate external APIs (like Stripe, PayPal, or specialized weather services). Each provider has its own unique naming conventions, error structures, and response shapes. If you call these directly throughout your Service Layer, your business logic becomes cluttered with provider-specific quirks, making it painful to switch providers later.

The Solution: The Adapter Interface

The Adapter Pattern acts as a "translator." You define a standard internal interface that your application expects. Then, you create an adapter class for each third-party service that maps its specific methods to your standard interface.

Imagine you need a payment service. Your application doesn't care how the provider works, only that it can process(amount).

// The Standard Interface your app expects
class PaymentAdapter {
  async pay(amount) { throw new Error("Method not implemented"); }
}

// Adapting a specific provider (e.g., Stripe)
class StripeAdapter extends PaymentAdapter {
  async pay(amount) {
    const response = await stripe.charges.create({ amount });
    return { success: true, transactionId: response.id };
  }
}

// Adapting a different provider (e.g., PayPal)
class PayPalAdapter extends PaymentAdapter {
  async pay(amount) {
    const response = await paypal.api.transfer(amount);
    return { success: response.status === 'ok', transactionId: response.guid };
  }
}

Why this matters

By injecting these adapters into your Service Layer (using your knowledge of Scoped Dependency Resolution), your core business logic remains completely agnostic of the external implementation. If you decide to migrate from Stripe to PayPal, you simply swap the adapter configuration. Your domain logic stays untouched, and your services remain clean and decoupled from the volatile nature of external API updates.

Key Takeaway: The Adapter Pattern decouples your application from external service quirks by wrapping disparate APIs behind a single, consistent interface.