# @api-ts/superagent-wrapper 中文文档

规范地址：https://npmcn.com/package/%40api-ts/superagent-wrapper/

版本：1\.3\.8
npm 元数据更新时间：2026-08-04T17:13:18.819Z
中文译文更新时间：2026-11-06T09:49:54.007Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：26.5 kB，15 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：superagent \*
- 首次发布：2022-04-18T21:18:11.960Z
- 最新版本发布：2026-08-04T17:13:18.494Z
- 近 30 天下载量：74834（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：50（近 12 个月 4 个）

## 中文简介

用超级剂使类型安全 HTTP 请求

## 安装

```sh
npm install @api-ts/superagent-wrapper
```

也可以使用：`pnpm add @api-ts/superagent-wrapper`、`yarn add @api-ts/superagent-wrapper`、`bun add @api-ts/superagent-wrapper`

## README

# @ api-ts/ 超剂- wrapper

将一个像谱与 `superagent`编号 :`supertest` 以创建已选中的 api 客户端.

## 开始

首先,定义或导入 `io-ts-http` api spec. (英语). 接下来将使用 本指南:

```typescript
import * as h from '@api-ts/io-ts-http';
import * as t from 'io-ts';
import { NumberFromString } from 'io-ts-types';

export const Example = t.type({
  foo: t.string,
  bar: t.number,
});

export const GenericAPIError = t.type({
  message: t.string,
});

export const PutExample = h.httpRoute({
  path: '/example/{id}',
  method: 'PUT',
  request: h.httpRequest({
    params: {
      id: NumberFromString,
    },
    body: {
      example: Example,
    },
  }),
  response: {
    ok: Example,
    invalidRequest: GenericAPIError,
  },
});

export const ExampleAPI = h.apiSpec({
  'api.example': {
    put: PutExample,
  },
});
```

`ExampleAPI` 然后可用于为其中任一创建一个类型安全 api 客户端 `superagent` 或者说 `supertest`这需要两个步骤: `superagent`编号 :`supertest` 举例来说, 然后把它绑在皮克上.

对于 `superagent`数字 :

```typescript
import { superagentRequestFactory, buildApiClient } from '@api-ts/superagent-wrapper';
import superagent from 'superagent';

import { ExampleAPI } from './see-the-above-example';

// The api root, in a real project probably coming from a config option
const BASE_URL = 'http://example.com/';

// Step one: wrap `superagent` and the api root
const requestFactory = superagentRequestFactory(superagent, BASE_URL);

// Step two: combine the request factory and imported api spec into an api client
// This is intended to be exported and used
export const apiClient = buildApiClient(requestFactory, ExampleAPI);
```

对于 `supertest` 过程几乎完全相同,但 `supertest` 自己处理 了解根 api url:

```typescript
import { supertestRequestFactory, buildApiClient } from '@api-ts/superagent-wrapper';
import supertest from 'superagent';

import { ExampleAPI } from './see-the-above-example';

// For the purposes of this guide, say we have an Express app that can be imported from the project.
// See the `supertest` docs for the options it has for instantiation.
import { app } from '../src/index';
const request = supertest(app);

// Step one: wrap the `supertest` request function created above
const requestFactory = superatestRequestFactory(request);

// Step two: combine the request factory and imported api spec into an api client
// This is intended to be exported and used
export const apiClient = buildApiClient(requestFactory, ExampleAPI);
```

结果 `apiClient` 然后可以进口到其他地方并使用:

```typescript
import { apiClient } from './api-client-example';

const doSomething = async () => {
  // The `api.example` here comes from the operation in the `ExampleAPI` definition from above
  const response = await apiClient['api.example']
    // The object passed to this function is type-checked against the request codec
    .put({ id: 42, example: { foo: 'hello', bar: 1 } })
    // This will use the set of response codecs to decode the response
    .decode();

  // The two main properties on `response` are `status` and `body`
  // If the value of `status` is checked, then TypeScript will infer the correct body type
  if (response.status === 200) {
    const { foo, bar } = response.body; // We know the correct body type here
  } else if (response.status === 400) {
    // The body is a GenericAPIError
    console.log(response.body.message);
  } else {
    // In case an unexpected status code comes back, or the response body does not correctly
    // decode, we can still access it as an `unknown` type.
    if (
      response.body &&
      typeof response.body === 'object' &&
      response.body.hasOwnProperty('message')
    ) {
      console.log(response.body.message);
    }
  }
};
```

为方便起见,a `decodeExpecting` 函数也被添加到请求中。 它接受一个 HTTP 状态代码和扔出,如果响应代码不匹配,或者它不匹配但 响应机构无法解码 .

```typescript
const expectOk = async () => {
  // The `api.example` here comes from the operation in the `ExampleAPI` definition from above
  const response = await apiClient['api.example']
    // The object passed to this function is type-checked against the request codec
    .put({ id: 42, example: { foo: 'hello', bar: 1 } })
    // This will use the set of response codecs to decode the response
    .decodeExpecting(200);

  const { foo, bar } = response.body;
};
```

## 常见问题

### @api-ts/superagent-wrapper 是什么？

用超级剂使类型安全 HTTP 请求

### 如何安装 @api-ts/superagent-wrapper？

在项目目录运行 npm install @api-ts/superagent-wrapper，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：superagent（\*）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @api-ts/superagent-wrapper 支持 TypeScript 吗？

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

### @api-ts/superagent-wrapper 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @api-ts/superagent-wrapper 可以商用吗？

@api-ts/superagent-wrapper 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @api-ts/superagent-wrapper 的下载量有多少？

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

### @api-ts/superagent-wrapper 还在维护吗？

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

