You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on May 25, 2021. It is now read-only.
A middleware that attachs HTTP client to communicate with the context during inter-service communications in Koa.
Communication between microservices must be efficient. With lots of microservices to complete a single request(transaction) successfully, each communication should have a context informations like the request id, content language, or something else. Koa HTTP Client will help inter-service communication with automatically attached context informations.
Installation
# Using NPM
$ npm install --save @kasa/koa-http-client
# Using Yarn
$ yarn add @kasa/koa-http-client
Use koa-http-client as a middleware for a koa app.
constKoa=require('koa');constrequestId=require('@kasa/koa-http-client');consthttpClient=require('@kasa/koa-http-client');constapp=newKoa();app.use(requestId());app.use(httpClient({retry: 3}));app.use(asyncctx=>{constuserService=ctx.http.extend({baseUrl: 'https://user.company.com:8080/'});letuser;try{const{ body }=awaituserService.get('/users/john');user=body.user;}catch(err){// Do something with error (HTTP status code 4xx or 5xx)}// Do something with user data});app.listen(3000);
API
Creating an middleware
You can create a new http client middleware by passing the relevant options to httpClient;
These are the available config options for the middleware. All is optional. The middleware attachs HTTP client with the context for each request.
{// HTTP headers to forward from Koa `ctx`forwardedHeaders: ['Accept-Language','Authorization'],// Client name to set `User-Agent` headeruserAgent: 'user-service/0.1.0',// HTTP header to get/set the request idrequestIdHeader: 'X-Service-Request-Id',// Milliseconds to wait for the server to end the response before aborting the requesttimeout: 20*1000,// Count to retry on the request errorsretry: 3,}
Credits
sindresorhus/got: koa-http-client was developed based on got. koa-http-client utilizes got.extend feature well!
Contributing
Bug Reports & Feature Requests
Please use the issue tracker to report any bugs or ask feature requests.