A light-weight javascript http request library built in conscious of middleware design pattern. (requires fetch api)
This project aims to reduce user mental effort and give user more control over the request process by provide only minimal features.
The middleware usage is as intuitive as using expressjs server middleware by using next() to pass control to the next middleware.
It will minimize effort to migrate from fetch to this library and work out of the box by just simply rename fetch to request in your project.
import { request } from 'express-http-client';
await request(
"https://example.com/api/v1/posts",
{
method: 'GET',
headers: {
'Authorization': 'Bearer ' + refresh
}
},
// response interceptors
[
//example response interceptor middleware
(data, next) => {
data.response.json().then(json => {
console.log(json);
next();
}).catch(error => {
next(error);
});
}
],
// request interceptors
[]
);
import {httpClient as expressHttpClient, logger, mockResponse} from 'express-http-client';
//create a new http client instance, you can create multiple http client instance for different purpose
let httpClient = expressHttpClient();
//add request interceptor middleware: example to add authorization header
httpClient.addRequestInterceptor(async (data, next) => {
data.request = new Request(data.request, {
// You can override any request properties here
headers: new Headers({
...Object.fromEntries(data.request.headers.entries()),
'Authorization': `Bearer token`
}),
});
next();
});
//add response interceptor middleware: example
httpClient.addResponseInterceptor(
//use built in logger interceptor middleware to log the request and response
logger(),
);
httpClient = httpClient.create("replace with your base url");
let response = await httpClient.send(`/api/v1/posts`);
data
: the data objectrequest
: the request objectresponse
: the response objectstore
: a map store for data persistence between interceptors
next
: the next function
import {httpClient as expressHttpClient, logger, mockResponse} from 'express-http-client';
let httpClient = expressHttpClient();
httpClient.addResponseInterceptor(
mockResponse(
true,
// supply the mock response mapping object here(url.method -> response)
{
"http://example.com/api/v1/posts": {
//mock response for GET request
"GET": ()=> new Response(JSON.stringify(
//mock response data
))
},
"http://example.com/api/v1/posts": {
//mock response for all request
"ALL": ()=> new Response(JSON.stringify(
//mock response data
))
},
}
)
)