Serving an endpoint with switching data sources
nodejsapiarchitecture

Serving an endpoint with switching data sources


On a project I was working on I was tasked with the following: Create an API that can serve two different data sources(one proxy, one local) using the same endpoint under a build flag / query flag, you might thing this is really easy to do and in reality it is. The problem arises when the only thing changing is your data source, not you data modelling. Take for example

See the problem?

For a couple of them I wouldn't mind having repeated code but once you have 50+ endpoints I'd like a more DRY approach or we might end up with a bunch of unnecessary bloat. Another problem with this approach is, if one of the requirements for the endpoint changes you have to make changes in two places, which can lead to all sorts of problems.

I want to preface this by saying that before this project I had never architectured an API before, thankfully team and I made what we think were good decisions. We made a lot of errors along the way but at the same time the amount of knowledge we gained was a pretty worthy tradeoff for so many headaches.

The Solution

Often times I see a lot of developers afraid of using classes for anything on JavaScript but they can be extremely useful when used properly

This approach of extending ServiceLocal from ServiceProxy will allow the endpoint to first hit our ServiceLocal, since the function GetPosts does not exists on our ServiceLocal class it will then use GetPosts from our ServiceProxy. Once it hits GetPostsData its where the magic happens. Since we overrode GetPostsData in our ServiceLocal even if the execution is happening in our ServiceProxy it will still execute GetPostsData from ServiceLocal.

Final Thoughts

Like I've said I've never had to architecture an API before, but we moved forward with this approach and we been pretty succesfull with it. Having granularity over which data source we use has been a life saver to keep our code DRY and not having to have our modeling step on our controller (I'm a sucker for separations of concern).

Anyways, that was my rant. I hope you find something of use in what I said,

love you, bye 👋🏼.