@biko/http-client
v0.1.3
Published
Wrapper for common http methods using different connectors (fetch, axios)
Downloads
15
Readme
Biko httpClient
Defines a wrapper on top of fetch
or any HTTP library like Axios.
That wrapper is in fact a TypeScript interface, which any underlying connector must meet. Currently, two connectors are provided:
- axios (completely functional)
- fetch (at this moment, not functional and only present as a proof-of-concept)
Installation
npm install --save @biko/http-client
API
setConnector(connector: HttpClientConnector)
Sets httpClient connector. It must be of type HttpClientConnector and own the following members:
- defaultConfig:
{ baseURL: Config; }
- sendGet:
(path: string, config?: Config)=> Promise<{ status: number; data: {} }>;
- sendPost:
(path: string, payload: {}, config?: Config)=> Promise<{ status: number; data: {} }>;
- sendPut:
(path: string, payload: {}, config?: Config)=> Promise<{ status: number; data: {} }>;
- sendPatch:
(path: string, payload: {}, config?: Config)=> Promise<{ status: number; data: {} }>;
- sendDelete:
(path: string, config?: Config)=> Promise<{ status: number; data: {} }>;
- addRequestInterceptor:
( onFulfilled?: (config: Config) => Config | Promise<Config>, onRejected?: (error: any) => any, ): number;
- addResponseInterceptor:
( onFulfilled?: (response: any) => any | Promise<any>, onRejected?: (error: any) => any, ): number;
- removeRequestInterceptor:
(id: number): void;
- removeResponseInterceptor:
(id: number): void;
Request and response interceptors are mainly based on Axios' interceptors, but they can be implemented using fetch or any other HTTP library. Please refer to them for further information.
Config
type is: { baseURL: string; [index: string]: any; }
setDefaultConfig(config: Config)
Sets HttpClientConnector's default config. This is useful when connections are always done to the same API, using the same tokens/auth data, etc.
Example:
// myHttpClient.ts
import * as httpClient from 'biko-http-client';
import * as httpClientConnector from 'biko-http-client/lib/connectors/axios';
httpClient.setConnector(httpClientConnector);
httpClient.setDefaultConfig({
baseURL: 'http://example.com/api',
headers: {
'X-user': 'myUsername',
'X-password': 'myPassword',
},
});
// Reexport only the functions your app is going to use
export const sendGet = httpClient.sendGet;
export const sendPost = httpClient.sendPost;
...
// ...or export the whole httpClient if your app uses all functions
export { httpClient };
// myComponent.ts
import { sendGet } from './myHttpClient';
sendGet('/my-path').then(response => {
console.log(response.status);
console.log(response.data);
});