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 🙏

© 2026 – Pkg Stats / Ryan Hefner

quick-fy

v1.1.0

Published

quick-fy 是一个轻量级、可扩展的基于 fetch 的 HTTP 请求库

Readme

quick-fy

npm version npm downloads bundle License

quick-fy 是一个轻量级、可扩展的基于 fetch 的 HTTP 请求库,适用于浏览器和 Node.js 环境。

特性

  • 基于原生 fetch API
  • 支持请求和响应拦截器
  • 提供全局钩子函数(onSuccess, onError, onComplete)
  • 中间件(Middleware)洋葱模型,支持网络层拦截和修改
  • 插件(Addon)系统,可打包复用 middleware + 拦截器
  • 内置常用中间件:logger、retry、timeout、body、params
  • 内置常用插件:headers
  • 支持自定义元数据传递
  • 类型安全,使用 TypeScript 编写

安装

npm install quick-fy

快速开始

import { createFy, fy } from 'quick-fy'

// 使用默认 fy 实例
const data = await fy.get('https://api.example.com/users')

// 创建自定义实例
const api = createFy({
  baseURL: 'https://api.example.com',
})

const users = await api.get<User[]>('/users')
const user = await api.post<User>('/users', {}, { meta: { data: { name: 'Alice' } } })

内置中间件

logger - 请求日志

记录请求和响应信息,包含耗时统计。

import { createFy } from 'quick-fy'
import { logger } from 'quick-fy/middlewares/logger'

const fy = createFy()
fy.use(logger())

// 输出示例:
// → GET https://api.example.com/users
// ← GET https://api.example.com/users 200 (123ms)

自定义回调:

fy.use(logger({
  onRequest: (method, url) => console.log(`Sending ${method} ${url}`),
  onResponse: (method, url, status, duration) => console.log(`${status} in ${duration}ms`),
  onError: (method, url, error, duration) => console.error(`Failed: ${error.message}`),
}))

| 选项 | 类型 | 默认行为 | |------|------|---------| | onRequest | (method, url) => void | 打印 → METHOD URL | | onResponse | (method, url, status, duration) => void | 打印 ← METHOD URL STATUS (durationms) | | onError | (method, url, error, duration) => void | 打印 ✗ METHOD URL message (durationms) |

retry - 自动重试

请求失败时自动重试,默认仅重试网络错误(TypeError)。

import { retry } from 'quick-fy/middlewares/retry'

fy.use(retry())

// 自定义配置
fy.use(retry({
  retries: 5,
  delay: 2000,
  shouldRetry: (error, attempt) => attempt < 3,
}))

| 选项 | 类型 | 默认值 | |------|------|--------| | retries | number | 3 | | delay | number (ms) | 1000 | | shouldRetry | (error, attempt) => boolean | 仅 TypeError 时重试 |

timeout - 请求超时

使用 AbortController 实现请求超时控制。

import { timeout, TimeoutError } from 'quick-fy/middlewares/timeout'

fy.use(timeout({ timeout: 5000 }))

try {
  await fy.get('/slow-api')
}
catch (error) {
  if (error instanceof TimeoutError) {
    console.log('请求超时')
  }
}

| 选项 | 类型 | 说明 | |------|------|------| | timeout | number (ms) | 必填,超时时间 |

body - JSON 请求体

自动将 meta.data 序列化为 JSON 请求体。

import { body } from 'quick-fy/middlewares/body'

fy.use(body())

await fy.post('/users', {}, { data: { name: 'Alice', age: 25 } })
// 自动设置 Content-Type: application/json 并序列化 body

params - 查询参数

自动将 meta.params 序列化为 URL 查询字符串。

import { params } from 'quick-fy/middlewares/params'

fy.use(params())

await fy.get('/users', {}, { params: { page: 1, size: 20 } })
// 实际请求: /users?page=1&size=20

内置插件

headers - 默认请求头

为所有请求添加默认 headers,不会覆盖已存在的同名 header。

import { headers } from 'quick-fy/addons/headers'

const fy = createFy({
  addons: [
    headers({
      headers: {
        'Authorization': 'Bearer token123',
        'X-App-Version': '1.0.0',
      },
    }),
  ],
})

Middleware

Middleware 作用于 fetch 调用的网络层,采用洋葱模型(onion model)执行。每个 middleware 接收 next 并返回新的处理函数,可以在请求前后添加逻辑。

import type { Middleware } from 'quick-fy'

// 自定义中间件
const rewriteUrl: Middleware = next => async (url, config, meta) => {
  return next(url.replace('api/v1', 'api/v2'), config, meta)
}

const fy = createFy()
fy.use(rewriteUrl)

中间件按注册顺序执行,形成洋葱模型:

A-before → B-before → fetch → B-after → A-after

调用 fy.clearMiddlewares() 可以移除所有中间件。

Addon

Addon 是 middleware 和拦截器的打包复用单元。一个 addon 是带有 install 方法的对象,install 接收完整的 FyInstance,可以注入 middleware、拦截器等能力。

import type { FyAddon } from 'quick-fy'

const myAddon: FyAddon = {
  install(fy) {
    fy.use(someMiddleware)
    fy.addBeforeInterceptor((method) => {
      return { ...method, meta: { ...method.meta, retries: 3 } }
    })
  }
}

// 注册方式
const fy = createFy({ addons: [myAddon] })
// 或动态注册
fy.useAddon(myAddon)

拦截器

拦截器作用于请求/响应的数据层。

const fy = createFy()

// 请求拦截器 - 在请求发送前修改请求
fy.addBeforeInterceptor((method) => {
  console.log('请求:', method.url)
  return method
})

// 响应拦截器 - 在响应返回前修改响应
fy.addAfterInterceptor((response) => {
  console.log('响应状态:', response.status)
  return response
})

// 清除拦截器
fy.clearBeforeInterceptors()
fy.clearAfterInterceptors()

三者关系

| 层级 | 能力 | 作用范围 | |------|------|---------| | Middleware | 网络层拦截,操作 url/config/meta,返回 Response | fetch 调用层 | | Interceptor | 请求/响应数据层,修改 Method 或 Response | beforeRequest / afterInterceptor | | Addon | 打包容器,组合 middleware + interceptor | 通过 install 注册到实例 |

API 参考

createFy(options)

创建一个新的 fy 实例。

| 字段 | 类型 | 说明 | |------|------|------| | baseURL | string | 基础 URL,非 http 开头的请求会自动拼接 | | beforeRequest | RequestInterceptor | 请求前拦截器 | | responded | RespondedHook | 全局响应钩子(onSuccess, onError, onComplete) | | middlewares | Middleware[] | 中间件数组 | | addons | FyAddon[] | 插件数组 |

FyInstance 方法

| 方法 | 说明 | |------|------| | request<T>(url, init?, meta?) | 发送请求 | | get<T>(url, init?, meta?) | GET 请求 | | post<T>(url, init?, meta?) | POST 请求 | | put<T>(url, init?, meta?) | PUT 请求 | | delete<T>(url, init?, meta?) | DELETE 请求 | | patch<T>(url, init?, meta?) | PATCH 请求 | | addBeforeInterceptor(interceptor) | 添加请求前拦截器 | | addAfterInterceptor(interceptor) | 添加响应后拦截器 | | clearBeforeInterceptors() | 清除所有请求前拦截器 | | clearAfterInterceptors() | 清除所有响应后拦截器 | | use(middleware) | 添加中间件 | | clearMiddlewares() | 清除所有中间件 | | useAddon(addon) | 动态注册插件 |

Meta 字段

通过第三个参数 meta 传递请求元数据:

| 字段 | 类型 | 说明 | |------|------|------| | responseType | 'json' \| 'text' \| 'blob' \| 'arraybuffer' | 指定响应数据类型 | | data | any | 请求体数据(需配合 body 中间件) | | params | Record<string, string \| number \| boolean> | 查询参数(需配合 params 中间件) |

FyError

请求失败时抛出,包含以下字段:

| 字段 | 类型 | 说明 | |------|------|------| | message | string | 错误信息 | | status | number | HTTP 状态码 | | response | Response | 原始 Response 对象 | | method | Method | 请求方法信息 |

许可证

MIT License © 2024-PRESENT XiaDeYu