A lightweight fetch wrapper with useful features like abort controller, applying middleware functions to request or response interceptor
npm install @asaje/fetch
or
yarn add @asaje/fetch
or
pnpm add @asaje/fetch
import { Fetch } from '@asaje/fetch';
export const api = new Fetch({
baseURL: 'https://jsonplaceholder.typicode.com',
});
export async function getTodo(id: number) {
const response = await api.get(`todos/${id}`);
console.log(response);
}
It's possible to set headers by just calling the setHeaders method.
api.setHeaders({
Authorization: 'Bearer 123',
'Content-Type': 'application/json',
});
A middleware is a function called just before the request is sent. The request config is inject as the middleware parameter
import { FetchRequest } from '@asaje/fetch';
api.addMiddleware((request: FetchRequest) => {
// Do what you want with the request
console.log(request);
return request; // Important to return the request
});
api.clearMiddlewares();
A response interceptor is a function called when the request is done and is applied to the response
import { FetchResponse } from '@asaje/fetch';
api.addInterceptor((response: FetchResponse) => {
// Do what you want with the response
console.log(response);
return response;
});
api.clearInterceptors();
api.bypassNgrokSecurity();