simplified-fetch@0.6.0 正式发布了!

2021-08-17 23:45:10 +08:00
 Benno

以前初学 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

Usage

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)

Example

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)
    }
}

Config & Ability

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

usage : executed before body formatter

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!

AbortController | MDN

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])

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()

runtime NodeJS

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...

1092 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/796427

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX