V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Benno
V2EX  ›  程序员

[email protected] 正式发布了!

  •  
  •   Benno · 2021-08-17 23:45:10 +08:00 · 1125 次点击
    这是一个创建于 1198 天前的主题,其中的信息可能已经有所发展或是发生改变。

    以前初学 React 并使用 fetch,写得到处都是重复的配置和.json()等代码,所以有必要封装一个请求对象,去抽离简化组件内的代码,而今天 simplified-fetch 终于足够成熟,去尝试完成这个任务了!

    核心功能简述:

    • 支持浏览器和 NodeJS
    • 管道式处理 fetch 请求前和响应后的代码逻辑
    • 集中的统一配置,可多实例
    • 使用 ts 开发,配合双端测试的保障

    下方为 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 & params

    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!

    • abort & timeout

    AbortController | MDN

    const [constroller, signal] = Api.aborts.someApi
    

    when you use as timeout, the number is accessible on signal.timeout and (error: AbortError).timeout

    • pipeline & control

    • pipeline (Api.request / Api.response)

      • manage orderable functions which pipes before request or after response.
      • pipes with different order executed in ascending numeric index order
      • pipes with same order executed in chronological order, like queue, first in first executed.
      • based on feature Ordinary OwnPropertyKeys
    • use/eject with order

      • use: @param ...pipe - pipe[0] as order should be nonnegative integer, rest should be function(s) as pipe(s). if order is not specified, set order to 0, which means will be executed in the first place.
      • eject: @param pipe - pipe[0] as order should be nonnegative integer, rest should be function(s) as pipe(s). if order is not specified, set order to the value which means executed first or normally 0.
      • order range: +0 ≤ i < 2^32 - 1
    • PipeRequest

    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

    • PipeResponse

    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

    • body

    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

    • FormData

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   6030 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 02:44 · PVG 10:44 · LAX 18:44 · JFK 21:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.