2.1.1 • Published 6 months ago

kbfetch v2.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

使用示例

发起 GET 请求的示例:

import kbfetch from 'kbfetch'
kbfetch.get('https://api.example.com/data', { id: 1 })
// OR
kbfetch.g('https://api.example.com/data', { params: { id: 1 } })

发起 POST 请求的示例:

kbfetch.post('https://api.example.com/data', { id: 1 })
// OR需要query参数
kbfetch.post('https://api.example.com/data', { id: 1 }, { params: { qa: 1 } })
// OR
kbfetch.p('https://api.example.com/data', { params: { qa: 1 }, body: { id: 1 } })

path 参数

kbfetch.get('https://baidu.com/:a/:b', { a: 1, b: 2 }).then(console.log)
kbfetch.post('https://baidu.com/:a/:b', { k: 2 }, { params: { a: 1, b: 2 } }).then(console.log)
kbfetch.p('https://api.example.com/:a/:b', { params: { a: 1, b: 2 }, body: { id: 1 } })

发起 其他 method 请求的示例:

// e.g. 1
kbfetch.p('https://baidu.com', { method: 'PUT' })
// e.g. 2
kbfetch.g('https://baidu.com', { method: 'PATCH' })

取消请求示例:

const ft = kbfetch.post('https://api.example.com/data', { id: 1 }, { canAbort: true })
ft.abort()

or timeout>=0

const ft = kbfetch.g('https://api.example.com/data', { params: { id: 1 }, timeout: 0 })
ft.abort()

设置公共参数比如 token

kbfetch.baseHeaders = { token: 'XXX' }

kbfetch.baseParams = { access_token: 'xxx' }

kbfetch.baseBody = { access_token: 'xxx' }

方法汇总

get: (url: string, params?: Record<string, any>, init?: KbFetchInit)

g: (url: string, init?: KbFetchInit & { params?: Record<string, any> })

post: (url: string, body?: Record<string, any>, init?: KbFetchInit)

p: (url: string, init?: KbFetchInit)

uploadFile: (url: string, file: File, init?: KbFetchInit)

其他method可以通过p方法或者g方法,实现

自定义选项

KbFetchInit 类型扩展了标准的 RequestInit,添加了一些可选的便捷属性:

  • baseUrl - API 地址的公共前缀
  • baseHeaders - 公共的 header,如 token
  • baseParams - 公共的 params,如企业微信的 access_token,没有放在 header 里面,可以在这里设置
  • baseBody - 公共 body
  • timeout - 请求超时时间(毫秒)
  • before - 修改/记录请求参数的回调函数
  • parser - 在返回 resolve 前解析响应的回调函数
  • after - 响应结果的回调函数
import kbfetch, { createKbFetch, kbfc } from 'kbfetch'
// kbfc等同于kbfetch
// 请求单独配置
kbfetch.post(url, data, kbFetchInit)
kbfetch.get(url, params, kbFetchInit)
// 创建自定义实例
const ft = createKbFetch(KbFetchInit)
// ft.get ft.post

fetch SSE 实现示例:

import kbfetch from 'kbfetch'
const sse = (name: string, params: { ondata: (data: string) => any } & Record<string, any>) => {
    const { ondata, ..._p } = params
    return kbfetch.post(name, _p, {
        timeout: 0,
        parser: rb => {
            if (!rb.body) return
            const reader = rb.body.getReader()
            const push = () => {
                // done 为数据流是否接收完成,boolean
                // value 为返回数据,Uint8Array
                return reader.read().then(({ done, value }) => {
                    if (done) return
                    ondata(new TextDecoder().decode(value))
                    // 持续读取流信息
                    return push()
                })
            }
            // 开始读取流信息
            return push()
        },
        after: v => v,
    })
}

无感知 token 刷新 实现示例:

let refreshTokenPromise
export const kfc = createKbFetch({
    baseUrl: 'https://xxx.xxx',
    after(res, req) {
        return res.then(async res => {
            // 此处使用401状态码表示token过期
            if (res.status !== 401) return res.data
            // @ts-ignore __retry 表示是否已经重试,避免多次触发
            if (userInfo.refreshToken && !req.init.__retry) {
                // @ts-ignore
                req.init.__retry = true
                const { userId, refreshToken } = userInfo
                await (refreshTokenPromise ||= kfc
                    .post('refreshUserToken', { user_id: userId, refresh_token: refreshToken })
                    .then(({ data }) => {
                        // 重新设置token
                        kfc.baseHeaders.token = data
                    })
                    .finally(() => (refreshTokenPromise = undefined)))
                return kfc.do(req.url, req.init)
            }
            // 此处可以,清除用户信息跳转登录页
            console.warn('登录信息已过期,请重新登录')
            return Promise.reject('token错误')
        })
    },
})
kfc.baseHeaders = { userId: 'xxx', token: 'xxx' }

更多关于 kbfetchInit 对象的详细信息,请参考原始的 TypeScript 定义文件。

1.1.0

7 months ago

1.0.9

7 months ago

1.0.8

7 months ago

2.1.1

6 months ago

2.1.0

6 months ago

1.0.7

9 months ago

1.0.6

9 months ago

1.0.2

11 months ago

1.0.1

12 months ago

1.0.0

12 months ago

1.0.5

11 months ago

1.0.4

11 months ago

1.0.3

11 months ago

0.0.26

1 year ago

0.0.27

1 year ago

0.0.20

2 years ago

0.0.21

2 years ago

0.0.22

2 years ago

0.0.11

2 years ago

0.0.12

2 years ago

0.0.13

2 years ago

0.0.14

2 years ago

0.0.15

2 years ago

0.0.16

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.19

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago