以前初学 React 并使用 fetch,写得到处都是重复的配置和.json()等代码,所以有必要封装一个请求对象,去抽离简化组件内的代码,而今天 simplified-fetch 终于足够成熟,去尝试完成这个任务了!
核心功能简述:
下方为 readme 简抄,预览的 md 渲染不尽人意,详见simplified-fetch | GitHub
Encapsulate a unified API request object to simplify the use of fetch | MDN and enhance it!
support borwser & node.js
import API, { urnParser } from 'simplified-fetch'
// generate 'Api' on globalThis/window/global(nodejs)
API.init({
newName?: string, // default:'Api', just for global access
baseURL?: string | URL,
method?: Methods, // default:'GET', 'POST', 'PUT'...
bodyMixin?: BodyMixin, // default:'json', 'text', 'blob', 'formData', 'arrayBuffer'
enableAbort?: boolean | number, // abort & timeout(ms)
pureResponse?: boolean, // default:false, whether resolved with Response.clone(),format: [response, pureResponse] or response
suffix?: string, // like .do .json
custom?: any, // anything you want to put inside and use it in pipeline
},{
someApi:{
urn: string | (params?: any) => string, // build in function: urnParser
config?: BaseConfig, // same as the above first param
},
someApi2:{...},
someApi3:'/xxx', // string as urn is supported
someApi4: (param?: any) => string, // function as urn is also supported
})
// somewhere.js
// all params are optional
await Api.someApi(body, params, config)
// enableAbort isn't supported in dynamic config
// support multi instances by create
const api = API.create({...}:BaseConfig, {...}:ApiConfig)
import API from "simplified-fetch"
import type { apiF, iApi, iApi_beta, APIConfig } from "simplified-fetch"
declare global {
// unable to hint when Api.aborts.someApiEnableAbort
// var Api: iApi & Apis
// able to hint when Api.aborts.someApiEnableAbort
var Api: iApi_beta<typeof configs> & Apis
}
// type your response
type response<T> = {
body: T,
ok: boolean, status: number, statusText: string, type: string,
}
interface Apis {
// you should type your own apiCallFunc, of course, you can bulid on this
someApi0: apiF<void, void, response<{ api0: number }>>,
someApi1: apiF<{ api1: number }, number, response<{ api1: string }>>,
// someApi2: apiF<any, any, response<{ api2: { api2: number } }>>,
}
// comment next line after config all Apis
const configs: APIConfig<Apis> = {
// necessary to enable hint when Api.aborts.someApiEnableAbort
// const configs = {
someApi0: '/someApi0',
someApi1: { urn: '/someApi1', config: { method: 'GET' } },
// someApi2: { urn: '/someApi2', config: { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } },
} as const
API.init({
baseURL: 'https://www.example.com',
method: 'POST',
mode: 'cors',
}, configs)
Api.request.use((url, config) => {
// @ts-ignore
config.headers['Authorization'] = getToken('example')
}, () => 'No Request')
const example = async () => {
try {
const { body, ok } = await Api.someApi0()
const { body: { api1 } } = await Api.someApi1({ api1: 1 }, 1)
} catch (e) {
console.warn(e)
}
}
BaseConfig is just an extension of second param of fetch(resource [, init]) fetch | MDN
configs are listed in Usage.
{
method: 'GET',
bodyMixin: 'json',
headers: {
"Content-Type": "application/json",
},
enableAbort: false,
pureResponse: false,
}
urnParser is based on Template strings or Template literals | MDN
if typeof urn is function, then invike it with params, and build url with returned string.
if typeof urn isn't function, then try to transform params and append to the search of URL (for type Object, FormData, URLSearchParams), or append to the pathname of URL (for type Array, String, Number).
// init
someApi:{
urn: urnParser`/xxx/${0}/${1}`
}
// somewhere.js
Api.someApi(body, ['user',[1,2,3]], config)
// getUrl: /xxx/user/1,2,3
in a way, you can do anything dynamicly on url, just set the placeholder index on, pass an Array, even an Object (index need to be string like: ${'key'} ).
ps: if you get better idea or create some beautiful way to format the url, please PR!
const [constroller, signal] = Api.aborts.someApi
when you use as timeout, the number is accessible on signal.timeout and (error: AbortError).timeout
Asynchronous executed just before fetch and after internal core operation with url & config
function: (url: URL, config: BaseConfig, [body, params, dynamicConfig], [someApi, urn, config, baseConfig]) => unknown
only the change to url & config will effect, others are just from your init/create config & call params
Not recommended: Change anything in params[2 | 3] will possibly causes bugs
Asynchronous executed just after get Response
function: (response: Response, request: Request, [resolve, reject]) => Promise<unknown>
invoke resolve | reject to end pipeline
Response and Request are both unique for each PipeResponse
const [order, pipes: PipeRequest[]] = Api.request.use(order: number | PipeRequest, ...functions: PipeRequest[])
// Math.abs&trunc(order), if get NaN/Infinity, may causes bugs(will executed in the last place).
// Personal Recommendation: 0b1111
const bools = Api.request.eject([order, pipes])
// remove function(s) in specific order from pipeline, return true means success
const [order, pipes: PipeResponse[]] = Api.response.use(order: number | PipeResponse, ...functions: PipeResponse[])
const bools = Api.response.eject([order, pipes])
control
PipeRequest function return true or any message, someApi will immediate reject with that, don't forget to catch it.
PipeResponse invoke resolve | reject to end pipeline
Failed to execute 'fetch' on 'Window': Request with ! GET/HEAD ! method cannot have body.
fetch.spec.whatwg.org constructor step-34
so body will be auto transformed by internal function to string, append to the search of URL (for type Object, FormData, URLSearchParams), or append to the pathname of URL (for type Array, String, Number).
other methods: Object and Array will be auto wrapped by JSON.stringfy()
when using FormData, please require this @web-std/form-data and set FormData global. Don't set this form-data global, and you can still use it local.
Reason: When body or params type FormData, internal core operation with url needs Web API compatible FormData.
Thanks to MDN, whatwg and Many blogers...