fetch-helper
fetch-helper
is a lightweight wrapper for the fetch API, only supported in browsers, if needed For use in node environment, please add fetch-node
global dependency.
import fetch from 'node-fetch';
globalThis.fetch = fetch;
If you are using a node version greater than v17.5.0
, you can directly enable the fetch
API with the --experimental-fetch CLI flag
API Documentation
fetchHelper
Promise fetchHelper(input[, init]);
input
: the requested url or Request
objectinit
: a configuration item object, including all the settings for the request, except all the configuration items that support native fetch Parameters also added the following parameters
baseURL
: this value will be prepended to input
unless input
is an absolute address or not a string
params
: URL parameters sent with the request, must be a plain object or a URLSearchParams
objectparamsSerializer
: allows custom serialization of params
parameter functionstransformRequest
: allows changing request parameters beforetransformResponse
: allows to change response data beforeadapter
: allows custom handling of fetch
requests, which makes testing easier.
ctx
is the context of the current request instance, through which you can get or modify the current request's input
, init
and other instance parameters
Returns a Response
of a Promise
/en-US/docs/Web/API/Response) object.
import fetchHelper from '@ckpack/fetch-helper';
fetchHelper('/sub-url', {
baseURL: 'https://example.com',
params: {
foo: 'bar',
},
});
create(init])
You can use the create
method to create an instance with a default config object
import fetchHelper from '@ckpack/fetch-helper';
const fetchInstance = fetchHelper.create({
method: 'GET',
mode: 'cors',
transformResponse(response) {
return response.json();
},
});
fetchInstance(`some url`);
example
Convert the returned result to json
const fetchHelper = fetchHelper(`some url`, {
transformResponse(response) {
return response.json();
},
});
Set the request's baseURL
const fetchInstance = fetchHelper.create({
baseURL: 'http://some.url',
});
fetchInstance('/sub-url');
Set request timeout
const fetchInstance = fetchHelper.create({
transformRequest(config) {
if(config.timeout){
const controller = new AbortController();
config.signal = controller.signal;
setTimeout(()=> {controller.abort()}, config.timeout)
}
return config;
},
});
fetchInstance('some url', {
timeout: 6000,
});
Custom adapter
const res = await fetchHelper('https://jsonplaceholder.typicode.com/comments', {
adapter: () => ({ id: 1 }),
});
For more examples, please refer to @ckpack/fetch-helper