Adapter Pattern: Adapting Data from the Outside World
Ivan Levenhagen
Posted on February 13, 2023
Often while building applications we consume data from outside services, and even save parts of it on our end. A very common mistake is adapting your architecture for these services, what you should do instead is adapt their data.
On Woovi our application communicates with various different applications from the outside world, also known as 3rd party apps. These applications have their own data modeling and doesn't always fit ours, so we must adapt their data to fit ours.
This approach have some benefits, such as decoupling. For example if we consume a email provider and then decide to change to another one in the future, rather than restructuring our architecture to fit the new provider, all we would need to do is create a new adapter and everything should stay working.
Another benefit is that it lets us not only learn from others modeling, we can try to evolve them to what we believe is the correct approach.
The Adapter Pattern
When consuming data from third party, before saving it to our database, we always run it through an adapter function. This function job is to accept a payload and return a payload for our structure, to avoid losing data, you can choose to save the original payload on a metadata field or something similar.
Creating an Adapter Function
Creating an Adapter Function is pretty simple, using a very contrived example, let's say we want consume a API for geo location, and save the latitude and longitude that it returns in our database.
In our data, we decided that both the latitude and longitude will be different fields, but when calling this api, it returns both values inside an array instead:
latLong: [40.689247, -74.044502]
Rather than altering our modeling to also accept an array, all we need to do is adapt this field to ours:
const latLongApiToLocation = (payload) => ({
latitude: payload.latLong[0],
longitude: payload.latLong[1],
});
While this is extremely simple, it makes the data ours and we're not dependent of this API, all we would need to do to replace it is create another of these functions, while maintaining the data in the structure we believe in.
If you want to work in a startup in its early stages, This is your chance. Apply today!
Woovi is a Startup that enables shoppers to pay as they please. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.
If you want to work with us, we are hiring!
Photo by Alexandre Debiève on Unsplash
Posted on February 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.