visit
Photo by on
On my previous post, I explained how a messaging system can help our system more scalable.
Back on when we use microservices architecture, the main concept is separating each service. After separating the services, now we have multiple services that deployed on the different host. It means our client — frontend services like Web, Mobile, or CLI — should retrieve data from the different host. This situation will become harder for us when we had more services. We should remember each service’s host so we can retrieve the data. Here how the system will look like.The current system design So, we need a mechanism to enable our frontend service call the backend services without knowing where the backend service hosted. How we can create the mechanism?
After API Gateway implemented
GET /feeds
to get all the feedsGET /feeds/{hashtag}
to get all feeds that contain the hashtagPOST /feeds
to create a new feedGET /hashtags
to get all the hashtagsGET /hashtags/{name}
to get single hashtag by its nameAPI Gateway reroute upcoming request
The index.js
will become our entry point. Here our index.js
And then access localhost:3000
and make sure it works. Now, we will create router as entry point to our API Gateway. First, create new directory at the root folder, name it routers
. Second, create four files on the router
directory, those are router.js
, apiAdapter.js
, feedService.js
, and hashtagService.js
. Here the purpose of each file
router.js
is to combine all the services endpointsapiAdapter.js
is to construct the API endpoint for each servicefeedService.js
is the file to reroute request to Feed ServicehashtagService.js
is the file to reroute request to Hashtag ServiceMake your router.js
, feedService.js
, and hashtagService.js
like the codes below
After Axios installed, now write this code on your apiAdapter.js
Then, update yourfeedService.js
and hashtagService.js
like code below
The purpose of the code above is to creating the HTTP client for each service. We construct new Axios object for each service and pass theBASE_URL
as parameter. The BASE_URL
is the base URL for each services. So, when there is incoming request to the API Gateway, it will be handle by the Axios object that constructed using the BASE_URL
before. Done! As simple as that.