@haul/http-client
v0.2.1
Published
custom api on top of request promise native
Downloads
1
Readme
@haul/http-client ·
An abstraction on top of request-native-promise
that makes functional composition easy.
Install
Using npm:
> npm install @haul/http-client
Using yarn:
> yarn add @haul/http-client
Usage
import { createClient, base, headers } from '@haul/http-client';
// Initialize a http client
const googleClient = createClient(
// Set the baseurl to https://johndoe.com
base('https://johndoe.com'),
// Set user agent header
headers({ 'User-Agent': 'robot' }),
);
;(async async () => {
await googleClient('/some-page');
// You can also pass a request config specific for one request
await googleClient('/another-page', {
method: 'POST',
headers: { 'User-Agent': 'Not a robot' },
body: {
foo: 'bar'
}
})
})();
base(string)
Configures base url for the client.
headers({ key: value })
Configure header(s) for the client.
query({ key: value })
Configure query string for the client.
Extending
The http-client relies heavily on middleware so the easiest way to extend behaviour is the create your own.
import { createClient, RequestConfig } from '@haul/http-client';
interface CustomRequestConfig extends RequestConfig {
myCustomProp: string;
}
export const myMiddleware = (myCustomProp: string) => (
opts: RequestConfig
): CustomRequestConfig => {
return {
...opts,
myCustomProp: myCcustomProp,
};
};
You can create more advanced middleware that is dependent on other values configured via other middleware:
export const myMiddleware = (myCustomProp: string) => (
opts: RequestConfig
): CustomRequestConfig => {
if (opts.headers && opts.headers['User-Agent'].toLowerCase() === 'robot') {
opts.headers = {
...opts.headers,
token: 'my robot token',
}
}
return opts;
};
Note that middleware is called in the order they are passed to createClient
. If you need to access a property
defined from another middleware, your middleware must be called after.