New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

quick-fy

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

quick-fy

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

latest
Source
npmnpm
Version
1.0.0
Version published
Weekly downloads
0
-100%
Maintainers
1
Weekly downloads
 
Created
Source

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,
}))
选项类型默认值
retriesnumber3
delaynumber (ms)1000
shouldRetry(error, attempt) => booleanTypeError 时重试

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('请求超时')
  }
}
选项类型说明
timeoutnumber (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,返回 Responsefetch 调用层
Interceptor请求/响应数据层,修改 Method 或 ResponsebeforeRequest / afterInterceptor
Addon打包容器,组合 middleware + interceptor通过 install 注册到实例

API 参考

createFy(options)

创建一个新的 fy 实例。

字段类型说明
baseURLstring基础 URL,非 http 开头的请求会自动拼接
beforeRequestRequestInterceptor请求前拦截器
respondedRespondedHook全局响应钩子(onSuccess, onError, onComplete)
middlewaresMiddleware[]中间件数组
addonsFyAddon[]插件数组

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'指定响应数据类型
dataany请求体数据(需配合 body 中间件)
paramsRecord<string, string | number | boolean>查询参数(需配合 params 中间件)

FyError

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

字段类型说明
messagestring错误信息
statusnumberHTTP 状态码
responseResponse原始 Response 对象
methodMethod请求方法信息

许可证

MIT License © 2024-PRESENT XiaDeYu

FAQs

Package last updated on 07 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts