# @alessiofrittoli/chain-functions 中文文档

规范地址：https://npmcn.com/package/%40alessiofrittoli/chain-functions/

版本：2\.8\.0
npm 元数据更新时间：2026-10-24T16:00:59.987Z
中文译文更新时间：2026-11-06T14:21:59.591Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40alessiofrittoli/chain-functions
原文对照：https://npmcn.com/package/%40alessiofrittoli/chain-functions/?lang=original
项目主页：https://github.com/alessiofrittoli/chain-functions#readme
源码仓库：https://github.com/alessiofrittoli/chain-functions

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：28.4 kB，11 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=24\.15\.0
- 运行依赖：0 个
- 首次发布：2024-12-22T12:45:20.837Z
- 最新版本发布：2026-10-24T16:00:59.626Z
- 近 30 天下载量：2994（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：13（近 12 个月 4 个）

## 中文简介

功能连锁容易

## 安装

```sh
npm install @alessiofrittoli/chain-functions
```

也可以使用：`pnpm add @alessiofrittoli/chain-functions`、`yarn add @alessiofrittoli/chain-functions`、`bun add @alessiofrittoli/chain-functions`

## README

# 链函数QQ

## 功能连锁容易

这个 `Chain` 分类为管理和执行职能链提供了一种效用。 链中的每个函数都可以可选地引用下个函数,从而能够灵活而可调和地进行执行. 这对诸如中间软件处理,数据转换,或以有条理的方式处理同步操作等情景特别有用.

 [![Latest version](https://img.shields.io/npm/v/@alessiofrittoli/chain-functions)](https://npmjs.org/package/@alessiofrittoli/chain-functions)[![Test coverage](https://coveralls.io/repos/github/alessiofrittoli/chain-functions/badge.svg) ](https://coveralls.io/github/alessiofrittoli/chain-functions)[![Socket Security score](https://socket.dev/api/badge/npm/package/@alessiofrittoli/chain-functions) ](https://socket.dev/npm/package/@alessiofrittoli/chain-functions/overview)[![npm downloads](https://img.shields.io/npm/dm/@alessiofrittoli/chain-functions.svg) ](https://npmjs.org/package/@alessiofrittoli/chain-functions)[![Dependencies](https://badgen.net/bundlephobia/dependency-count/@alessiofrittoli/chain-functions) ](https://bundlephobia.com/package/@alessiofrittoli/chain-functions)[![Dependencies status](https://img.shields.io/librariesio/release/npm/@alessiofrittoli/chain-functions)](https://libraries.io/npm/%40alessiofrittoli%2Fchain-functions)

 [![minified](https://badgen.net/bundlephobia/min/@alessiofrittoli/chain-function)](https://bundlephobia.com/package/@alessiofrittoli/chain-function)[![minizipped](https://badgen.net/bundlephobia/minzip/@alessiofrittoli/chain-function) ](https://bundlephobia.com/package/@alessiofrittoli/chain-function)[![Tree shakable](https://badgen.net/bundlephobia/tree-shaking/@alessiofrittoli/chain-function)](https://bundlephobia.com/package/@alessiofrittoli/chain-function)

[![Fund this package](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

### 目录

-   [开始](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-getting-started)
-   [发展](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-development)
    -   [地方发展](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-local-development)
    -   [生产建设](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-production-build)
    -   [单位测试](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-unit-tests)
        -   [进行覆盖测试](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-run-tests-with-coverage)
    -   [捐款](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-contributing)
    -   [警卫](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-security)
-   [API 参考](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-api-reference)
    -   [`Chain` 类](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-chain-class)
    -   [类型](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-types)
-   [关键特性](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-key-features)
-   [实例](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-examples)
-   [贷项](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-made-with-)

* * *

### 开始

运行以下命令开始使用 `chain-functions` 在您的项目中:

```bash
npm i @alessiofrittoli/chain-functions
```

或使用 `pnpm`

```bash
pnpm i @alessiofrittoli/chain-functions
```

* * *

### 发展

运行以下开始开发

```shell
nvm use

pnpm i
```

#### 地方发展

运行以下

```shell
pnpm dev
```

这将生成未忽略的输出代码, 源图并启用源文件监视器 .

* * *

#### 生产建设

运行以下来创建本地生产建筑

```shell
pnpm build
```

这将生成没有源代码的已修改输出代码 .

* * *

#### 单位测试

通过运行下列程序运行所有定义的测试套件 :

```shell
# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci
```

* * *

##### 进行覆盖测试

然后开始使用 HTTP 服务器服务覆盖文件 `./coverage` 文件夹.

您可以在您第一次运行此命令时看到空白页 。 只需刷新浏览器即可看到更新 .

```shell
pnpm test:coverage:serve
```

* * *

#### 捐款

献礼真受欢迎!

请参看 [贡献文件](https://npmcn.com/package/%40alessiofrittoli/chain-functions/CONTRIBUTING.md) 了解如何开始为该项目作出贡献的更多信息.

帮助更新此项目 [GitHub 赞助商](https://github.com/sponsors/alessiofrittoli)。 。 。 .

[![GitHub Sponsor](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

* * *

#### 警卫

如果你认为你发现了安全漏洞 我们鼓励你 **_负责地披露此事,不公开问题_**我们将调查所有合法的报告。 电子邮件 `security@alessiofrittoli.it` 披露任何安全弱点.

* * *

### API 参考

#### `Chain` 类

用于管理和执行职能链的效用类别.

##### 静态方法

###### `Chain.functions()`

递归性地执行一系列函数.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `chain` | `ChainFactory<T,U>` | \- 说吧 | 要执行的功能链 . |
|  |  |  | 这必须是一系列功能(`ChainLink<T>`),其中最后一个函数为 LastChainLink 类型。 见 [类型](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-types) 供进一步参考. |
| `index` | `number` | `0` | (备选) 执行的起始索引 . |

* * *

回返

类型 : `T | U`

链执行的结果,它与链的功能类型相匹配(`T` 或者说 `U`) (中文(简体) ).

见 [类型](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-types) 供进一步参考.

* * *

掷出

`Error` 如果在指定的索引中找不到函数.

* * *

示例

```ts
import type { ChainLink, LastChainLink, ChainFactory } from '@alessiofrittoli/chain-functions/types'
import { Chain } from '@alessiofrittoli/chain-functions'

type ChainFunction = () => string

const function1: ChainLink<ChainFunction> = next => () => `1-${next()}`
const function2: ChainLink<ChainFunction> = next => () => `2-${next()}`
const function3: LastChainLink<ChainFunction> = () => () => 'end'

const chain: ChainFactory<ChainFunction> = [function1, function2, function3]
const result = Chain.functions(chain)()

console.log(result) // Output: '1-2-end'
```

* * *

###### `Chain.isLast()`

确定给定的函数是否是按键投出最后一个函数所需的链条中的最后一个函数 `LastChainLink<U>`。 。 。 .

这种方法主要用于内部 `Chain.functions()` 用于确定链式执行何时终止的方法.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `chain` | `ChainFactory<T,U>` | \- 说吧 | 职能链. 见 [类型](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-types) 供进一步参考. |
| `fn` | `ChainLink<T>|LastChainLink<U>` | \- 说吧 | 键入 Cast 函数 。 这既可以是常规链条链条,也可以是最后一个链条链条. 见 [类型](https://npmcn.com/package/%40alessiofrittoli/chain-functions/#readme-types) 供进一步参考. |
| `index` | `number` | `0` | (备选) 当前函数索引 `Chain.functions()` 复相会相. |

* * *

回返

类型 : `boolean`

回返 `true` 如果给定的函数是链条中最后一个函数, `false` 否则.

* * *

#### 类型

##### `ChainFunction`

代表任何可以作为链条的一部分引用的可调用函数.

这在内部用于打入其他类型 `template` 参数.

##### `ChainLink<T extends ChainFunction = ChainFunction>`

代表一个职能链中的单一环节.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `next` | `T` | 链中下个功能. 返回类型必须是类型 `T`。 。 。 . |

* * *

回返

类型 : `T`

可以被引用为链条一部分的函数.

* * *

##### `LastChainLink<T extends ChainFunction = ChainFunction>`

代表一个职能链中的最后一个环节。 与 `ChainLink`,它不接受 `next` 参数.

回返

类型 : `T`

可以被引用为链条中最后一步的函数.

* * *

##### `ChainFactory<T extends ChainFunction = ChainFunction, U extends ChainFunction = T>`

作为数组表示完整的函数链.

###### 结构

-   可包含任何数量 `ChainLink<T>` 函数.
-   数组中最后一个元素必须是 `LastChainLink<U>`。 。 。 .

* * *

### 关键特性

-   链路链接功能高度自定义化.
-   链路链接功能可以是 `async` 函数.
-   最后一个链条链条可以返回不同的类型(`U`除外 `T` 从标准 `ChainLink`。 。 。 .

* * *

### 实例

#### 导入库

```ts
// importing the main `Chain` class
// importing types
import type { ChainLink, LastChainLink, ChainFactory } from '@alessiofrittoli/chain-functions/types'
import { Chain } from '@alessiofrittoli/chain-functions'
```

基本用途

```ts
// define the chain link function type
type ChainFunction = () => string

// declare chain link functions
const function1: ChainLink<ChainFunction> = next => () => `1-${next()}`
const function2: ChainLink<ChainFunction> = next => () => `2-${next()}`
// declare the last chain function
const function3: LastChainLink<ChainFunction> = () => () => 'end'

// declare the chain array
const chain: ChainFactory<ChainFunction> = [function1, function2, function3]
// execute the chain array
const result = Chain.functions(chain)()

console.log(result) // Output: '1-2-end'
```

* * *

预用

```ts
type ChainFunctionProps = {
  someProperty: string
  firstFunction?: boolean
  secondFunction?: boolean
  thirdFunction?: boolean
}
// define the chain link function type
type ChainFunction = (props: ChainFunctionProps) => ChainFunctionProps

// declare chain link functions
const function1: ChainLink<ChainFunction> = next => props => {
  // edit properties
  props.someProperty = 'Edited by 1st function'
  props.firstFunction = true
  // call the next function in the chain
  return next(props)
}

const function2: ChainLink<ChainFunction> = next => props => {
  props.secondFunction = true

  if (props.someProperty === 'Edited by 1st function') {
    // stop chain execution if some condition is met.
    return props
  }

  // call the next function in the chain
  return next(props)
}

// declare the last chain function
const function3: LastChainLink<ChainFunction> = () => props => {
  props.thirdFunction = true
  return props
}

// declare the chain array
const chain: ChainFactory<ChainFunction> = [function1, function2, function3]
// declare the initial state
const initialState: ChainFunctionProps = {
  someProperty: 'Initial value',
  firstFunction: false,
  secondFunction: false,
  thirdFunction: false,
}
// execute the chain array with initial state
const result = Chain.functions(chain)(initialState)

console.log(result)
// Output: {
//  someProperty    : 'Edited by 1st function',
//  firstFunction   : true,
//  secondFunction  : true,
//  thirdFunction   : false,
// }
```

* * *

" Last ChainLink " 有自定义返回类型

```ts
type ChainFunction = () => string
type LastChainFunction = () => boolean

const function1: ChainLink<ChainFunction> = next => () => `1-${next()}`
const function2: ChainLink<ChainFunction> = next => () => `2-${next()}`
const function3: LastChainLink<LastChainFunction> = () => () => true

const chain: ChainFactory<ChainFunction, LastChainFunction> = [function1, function2, function3]
const result = Chain.functions(chain)()

console.log(result) // Outputs: '1-2-true'
```

* * *

" ChainLink " 职能与承诺

```ts
type ChainFunction = () => string | Promise<string>

const function1: ChainLink<ChainFunction> = next => async () => {
  // simulate a long task running
  await new Promise<void>(resolve => setTimeout(resolve, 5000))
  return `1-${next()}`
}
// this function is executed once `function1` Promise get resolved.
const function2: ChainLink<ChainFunction> = next => () => `2-${next()}`
const function3: LastChainLink<ChainFunction> = () => () => 'end'

const chain: ChainFactory<ChainFunction> = [function1, function2, function3]
const result = Chain.functions(chain)() // `result` is now a promise

console.log(await result) // Outputs: '1-2-end'
```

* * *

Next.js 中间软件链

```ts
// src/middleware.ts

import type { ChainFactory, ChainLink, LastChainLink } from '@alessiofrittoli/chain-functions/types'
import { NextMiddleware, NextResponse } from 'next/server'
import { Chain } from '@alessiofrittoli/chain-functions'

type Middleware = ChainLink<NextMiddleware>
type LastMiddleware = () => NextResponse<unknown>
type MiddlewareFactory = ChainFactory<NextMiddleware, LastMiddleware>

const middleware1: Middleware = next => async (request, event) => {
  const { nextUrl } = request

  if (nextUrl === '...') {
    const rewriteUrl = '...'
    return NextResponse.rewrite(rewriteUrl)
  }

  return next(request, event)
}

const middleware2: Middleware = next => async (request, event) => {
  const response = await next(request, event)

  // do something with `response` returned by the next middleware.
  // ...

  return response
}

// ensures `NextResponse.next()` is called if no one stops the chain.
const lastMiddleware: LastChainLink<LastMiddleware> = () => () => NextResponse.next()

const middlewares: MiddlewareFactory = [middleware1, middleware2, lastMiddleware]

export const config = {
  matcher: [
    /**
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api/|_next|.*\\..*).*)',
  ],
}

// note that we do not execute the chain like in the previous examples since Next.js is responsible for the execution, providing `request` and `event` parameters to the `middleware` functions.
export default Chain.functions(middlewares)
```

* * *

### 由 所制

<table><tbody><tr><td><img alt="avatar" src="https://avatars.githubusercontent.com/u/35973186" loading="lazy" decoding="async" referrerpolicy="no-referrer"></td><td><table><tbody><tr><td><a href="https://github.com/alessiofrittoli" rel="nofollow noopener noreferrer">阿莱西奥·弗里托利</a></td></tr><tr><td><small><a href="https://alessiofrittoli.it/" rel="nofollow noopener noreferrer">https://alessiofrittoli.it (英语)</a> | <a href="mailto:info@alessiofrittoli.it" rel="nofollow noopener noreferrer">(原始内容存档于2018-10-21) (英语). info.it</a></small></td></tr></tbody></table></td></tr></tbody></table>

## 常见问题

### @alessiofrittoli/chain-functions 是什么？

功能连锁容易

### 如何安装 @alessiofrittoli/chain-functions？

在项目目录运行 npm install @alessiofrittoli/chain-functions，或使用 pnpm add / yarn add / bun add。

### @alessiofrittoli/chain-functions 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @alessiofrittoli/chain-functions 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @alessiofrittoli/chain-functions 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.15\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @alessiofrittoli/chain-functions 可以商用吗？

@alessiofrittoli/chain-functions 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @alessiofrittoli/chain-functions 的下载量有多少？

根据 npm 官方下载统计，@alessiofrittoli/chain-functions 在 2026/10/06 – 2026/11/04 这 30 天内被下载 2,994 次，日均约 100 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @alessiofrittoli/chain-functions 还在维护吗？

最新版本 2\.8\.0 发布于 2026/10/25（14 天前）；至今共发布 13 个版本，其中过去 12 个月发布了 4 个；首次发布于 2024/12/22。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

