The “Service Adapter” pattern is designed to manage external API calls in Node JS API projects. This pattern has the additional benefit of managing different versions of the same API. This pattern should be viewed as a compliment to the “Service Stack” pattern.
This pattern consists of two main components:
- Adapter Factory
The adapter class should encapsulate all code required to interact with the external API. A method should be provided to take in all required headers, security tokens or request object that is required to complete the external calls. This method will be called by the factory prior to releasing an object to a calling service. The exposed methods should consume and return known objects. Any object transformations must be handled by the adapter. There should be a singleton function provided by the adapter which indicates API version compatibility as well as the supported endpoints.
The adapter factory allows the service layer to retrieve a new adapter for the version that needs to be called. The adapter factory methods should expose the required initialization parameters and a version parameter to help select the proper adapter.
A service that needs to make external API calls will request a new adapter from the factory by providing the external API version and other required parameters. The adapter can then be invoked from the service layer or passed to the coordinator layer for use in the business logic.
Initialization begins once the application starts. The adapter factory will be called and all adapter definitions will be cached. A pool of adapter instances should be created for each definition to enhance performance. Once a request for an adapter is made, the factory will retrieve an instance from the pool and call the initialization method. A simple flow is provided below.
During a request, the service will be responsible for getting the adapter and then either using it to make calls or passing it to the coordinator for inclusion in the business logic. Using the diagram below, the following flow is executed. For a more detailed look at the service flow, refer to the “Service Stack” pattern.
- A request is received by the service.
- The service requests an adapter by calling the adapter factory.
- The adapter factory will pull a cached adapter and call the initialize method.
- The adapter will be returned to the service which then calls an adapter method.
- The adapter takes the input parameters and converts them into objects suitable for the external API call.
- The adapter then calls the API and converts the response into a format the service understands.
- The service then passes the response to the coordinator to be processed by the business logic.
- Once the processing is complete, the coordinator returns to the service which then sends a response to the calling entity.