Adapter

Wrapper

Escrito por Darjus Kazakevic · revisado el

A translator you own, at the edge of someone else's API.

You need a payment provider, a geocoder or a mail service. You get their vocabulary: their field names, their units, their error codes. Once those appear in your use-cases, the vendor's next breaking change breaks your code in many places.

An Adapter is a small class or function you own. It implements an interface written in your words and calls the vendor underneath. Their names and failures stop in that one file. In Hexagonal Architecture this is exactly an adapter behind a port, and the in-memory fake for tests is a second adapter.

En esencia — Wrap an incompatible interface in the one your code already expects, so two things never designed to work together can, without either one changing.

Cuándo recurrir a él

Recurre a él cuando

  • A vendor SDK's names, units or error codes are leaking into use-cases
  • You may swap the provider, or need a fake of it for tests
  • Legacy code you cannot change has an awkward interface

Reconsidéralo cuando

  • Both interfaces are yours: change one of them instead
  • A stable standard API that your code would name the same way
  • A one-off script that calls the vendor once

Conceptos clave

Target interface (port)
The interface your code wants, written in your words. It knows nothing about any vendor.
Adaptee
The thing you cannot or should not change: a vendor SDK, a legacy module, a browser API.
Adapter
The class or function that implements the target and calls the adaptee. It maps names, converts units, and turns their errors into your errors.
In modern TypeScript
No inheritance is needed. A function that returns an object literal matching the interface is a complete adapter. Use a class if you prefer, but it adds nothing here.

Reglas de diseño

Write the port in your words
Name the interface after what your code needs, not after what the vendor offers. A port that copies the SDK method for method just moves the leak behind one extra file.
Translate their failures, not only their calls
Their error codes are part of their vocabulary. Catch them in the adapter and throw your own types, so no use-case compares a vendor string.
Keep business logic out of the adapter
An adapter maps and converts. Decisions, such as whether a refund is allowed, belong in the use-case. Logic hidden in an adapter is lost when you change provider.

Errores habituales

  • A port that copies the SDK method for method. The leak just moves behind one extra file.
  • Vendor types (Stripe.Refund) in the port's signatures, so the domain imports the SDK after all.
  • Business rules inside the adapter, lost when you change provider.
  • Turning every vendor error into one generic failure, so callers cannot tell "already refunded" from "network down".