@ckpack/fetch-helper
@ckpack/fetch-helper
is a lightweight wrapper for the Fetch API. It needs to be used in a browser that supports Fetch
API or Node.js
(version less than v18.0.0).
API Documentation
fetchHelper<T=Response>(input: RequestInfo, init?: FetchHelperInit | undefined): Promise
input
: the requested url or Request
objectinit
: a configuration item object, including all the settings for the request, supports all the configuration item parameters of the native fetch , and added the following parameters
baseURL
: if the passed in input
is not an absolute address, the value will be prepended to input
,params
: URL parameters sent with the request, must be a plain object or a URLSearchParams
objectparamsSerializer
: set custom serializer params
parameter functiontransformRequest
: allows changing request parameters before the request is madetransformResponse
: allows changing response data after request responseadapter
: Allows custom handling of requests, which makes testing easier.
Returns a Promise
object, the default is [Response
](https://developer. mozilla.org/en-US/docs/Web/API/Response) type, other types can also be returned through transformResponse
import fetchHelper from '@ckpack/fetch-helper'
fetchHelper('/comments', {
baseURL: 'http://jsonplaceholder.typicode.com',
params: {
id: 1,
},
})
fetchHelper.create
Create a new fetchHelper
instance with custom configuration.
const instance = fetchHelper.create({
baseURL: 'http://jsonplaceholder.typicode.com',
})
fetchHelper.default
Permanently modify the request instance configuration via the default
attribute:
instance.default.baseURL = 'http://localhost:3000'
fetchHelper[method]
For convenience, aliases are provided for all supported request methods.
fetchHelper.request(config)
fetchHelper.get(url, params?, config?)
fetchHelper.head(url, params?, config?)
fetchHelper.options(url, params?, config?)
fetchHelper.connect(url, params?, config?)
fetchHelper.trace(url, params?, config?)
fetchHelper.delete(url, body?, config?)
fetchHelper.post(url, body?, config?)
fetchHelper.put(url, body?, config?)
fetchHelper.patch(url, body?, config?)
example
Set the requested configuration
create(defaultConfig?: FetchHelperInit)
You can use the create
method to create an instance with a default config object
import fetchHelper from '@ckpack/fetch-helper'
const instance = fetchHelper.create({
baseURL: 'http://jsonplaceholder.typicode.com',
})
instance('/comments', {
params: {
id: 1,
},
})
instance.default.baseURL = 'http://localhost:3000'
instance('/comments', {
params: {
id: 1,
},
})
await instance('/comments', {
baseURL: 'http://localhost:3000',
params: {
id: 1,
},
})
set request method
You can set the request method through the method
parameter, such as GET
, POST
await fetchHelper('http://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({ firstName: 'Fred', lastName: 'Flintstone' }),
})
await fetchHelper.post('http://jsonplaceholder.typicode.com/posts', JSON.stringify({ firstName: 'Fred', lastName: 'Flintstone' }), {
headers: {
'Content-type': 'application/json',
},
})
set query string params
Set the query string (query string), the parameter is serialized and spliced after url
fetchHelper('/comments', {
baseURL: 'http://jsonplaceholder.typicode.com',
params: {
limit: 10,
page: 2,
ids: [1, 2, 3]
},
})
paramsSerializer
paramsSerializer
is an optional function responsible for serializing params
, by default new URLSearchParams(params).toString()
is used to complete serialization
fetchHelper('/comments', {
baseURL: 'http://jsonplaceholder.typicode.com',
params: {
limit: 10,
page: 2,
ids: [1,2,3]
},
paramsSerializer: (params) => Qs.stringify(params, {arrayFormat: 'brackets'},
})
transformRequest
The request parameter configuration can be changed through transformRequest
. By default, fetch
passes parameters through application/json
and requires manual serialization of JSON.stringify(body)
, and then set Content-type
in Headers
to application
/json, you can simplify this way with
transformRequest`
const resuest = fetchHelper.create({
baseURL: 'http://jsonplaceholder.typicode.com',
transformRequest(init) {
const { body } = init
if (typeof body === 'object' && !(body instanceof FormData || body instanceof URLSearchParams)) {
const headers = new Headers(init.headers)
headers.set('Content-type', 'application/json')
init.headers = headers
init.body = JSON.stringify(body)
}
return init
},
})
const res = await resuest.post('/posts', { firstName: 'Fred', lastName: 'Flintstone' })
Transform the request result via transformResponse
const fetchHelper = fetchHelper('http://jsonplaceholder.typicode.com/comments', {
transformResponse(response) {
return response.json()
},
})
const fetchHelper = fetchHelper<{ id: number }[]>('http://jsonplaceholder.typicode.com/comments', {
transformResponse(response) {
return response.json()
},
})
Set request timeout
const instance = fetchHelper.create({
transformRequest(config) {
if (config.timeout) {
const controller = new AbortController()
config.signal = controller.signal
setTimeout(() => controller.abort('timeout'), config.timeout)
}
return config
},
})
await instance('http://jsonplaceholder.typicode.com/comments', {
timeout: 6000,
})
Custom adapter
const fetchResponse = await fetchHelper('http://jsonplaceholder.typicode.com/comments', {
params: {
limit: 1,
page: 2
},
adapter(input) {
return new Response(`${input}`)
},
})
console.log(await fetchResponse.text())
For more examples, please refer to @ckpack/fetch-helper