npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kbfetch

v1.1.0

Published

一个轻量基于fetch封装的API请求工具库

Downloads

148

Readme

使用示例

发起 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 定义文件。