# @di-framework/http 中文文档

规范地址：https://npmcn.com/package/%40di-framework/http/

版本：6\.1\.0
npm 元数据更新时间：2026-10-11T22:42:18.460Z
中文译文更新时间：2026-11-12T06:40:48.468Z
软件包许可：\(MIT OR Apache-2\.0\)

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

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

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

- 包体积（解压后）：79.3 kB，14 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：typescript ^5，@di-framework/core ^6
- 首次发布：2026-08-02T16:07:19.233Z
- 最新版本发布：2026-10-11T22:42:18.115Z
- 近 30 天下载量：3136（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：40（近 12 个月 40 个）

## 中文简介

延长带有 HTTP 特性的 二框架

## 安装

```sh
npm install @di-framework/http
```

也可以使用：`pnpm add @di-framework/http`、`yarn add @di-framework/http`、`bun add @di-framework/http`

## README

# @di-framework/http (韩语)

轻量级 TypeScript 装饰器和用于类型安全的路由器 [路线](https://github.com/kwhitley/itty-router)。包括一个构建时的 OpenAPI 3.1 生成器。 从 `itty-decorators`。 。 。 .

## 特征

-   **类型安全运行**数字 : `TypedRouter` 为请求机构、响应类型和上下文提供全面的TypeScript支持.
-   **自动 JSON 执行**: 自动验证 `Content-Type: application/json` 用于突变方法(POST,PUT,PATCH).
-   **多部分支助**: 打开 `multipart/form-data` 处理 `Multipart<T>` 财务报告和审定财务报表 `{ multipart: true }`。 。 。 .
-   **声明元数据**: 使用 `@Controller` 财务报告和审定财务报表 `@Endpoint` 用代码直接记录您的 API 逻辑的装饰 .
-   **DI 一体化**数字 : `@Controller` 组成核心 DI `@Container` 装饰器,所以控制器是自动注册的,可以使用 `@Component` 注射和 `useContainer().resolve(...)`。 。 。 .
-   **OpenAPI 3.1 支持**: 在构建时从您的代码生成完整的 OpenAPI 规格 .
-   **最小脚印**: 在超光线上方建造 `itty-router`。 。 。 .

## 安装

```bash
# Install the HTTP package and the core DI framework (peer dependency)
bun add @di-framework/http @di-framework/core
# or
npm install @di-framework/http @di-framework/core
```

## 快速启动

### 1\. 创建控制器(DI-aware)

使用装饰器和 `TypedRouter`。控制器会自动在 DI 容器中注册,从而可以注入服务并解析控制器实例.

```typescript
import {
  TypedRouter,
  json,
  type RequestSpec,
  type ResponseSpec,
  type Json,
  Controller,
  Endpoint,
} from '@di-framework/http';
import { Component, Container } from '@di-framework/core/decorators';
import { useContainer } from '@di-framework/core/container';

const router = TypedRouter();

type EchoPayload = { message: string };
type EchoResponse = { echoed: string; timestamp: string };

// Example DI-managed service
@Container()
export class LoggerService {
  log(msg: string) {
    console.log(msg);
  }
}

@Controller()
export class EchoController {
  // Because @Controller composes the core @Container decorator, this class is
  // automatically registered with the DI container. We can inject services.
  @Component(LoggerService)
  private logger!: LoggerService;

  echoMessage(message: string): EchoResponse {
    this.logger.log(`Echoing: ${message}`);
    return { echoed: message, timestamp: new Date().toISOString() };
  }

  @Endpoint({
    summary: 'Echo a message',
    description: 'Returns the provided message with a server timestamp.',
    responses: {
      '200': { description: 'Successful echo' },
    },
  })
  static post = router.post<RequestSpec<Json<EchoPayload>>, ResponseSpec<EchoResponse>>(
    '/echo',
    (req) => {
      // Demonstrate auto DI registration: resolve the controller instance from
      // the global container without any manual registration.
      const controller = useContainer().resolve(EchoController);
      return json(controller.echoMessage(req.content.message));
    },
  );
}

// Add a simple GET route
router.get('/', () => json({ message: 'API is healthy' }));

export default {
  fetch: (request: Request, env: any, ctx: any) => router.fetch(request, env, ctx),
};
```

### 2\. 多段文件上传

使用 `Multipart<T>` 财务报告和审定财务报表 `{ multipart: true }` 接受 `multipart/form-data` 而不是JSON。 而不是JSON。 处理者收到 `req.content` 类型为 `FormData`。 。 。 .

```typescript
import {
  TypedRouter,
  json,
  type RequestSpec,
  type ResponseSpec,
  type Multipart,
} from '@di-framework/http';

const router = TypedRouter();

type UploadPayload = { files: File[] };
type UploadResult = { filenames: string[] };

router.post<RequestSpec<Multipart<UploadPayload>>, ResponseSpec<UploadResult>>(
  '/upload',
  (req) => {
    // req.content is typed as FormData
    const files = req.content.getAll('files') as File[];
    return json({ filenames: files.map((f) => f.name) });
  },
  { multipart: true },
);
```

### OpenAPI 生成

该套件会曝光CLI-独立OpenAPI操作. 控制器装入, 文档生成和写入是明确的:

```ts
import { generateOpenAPIDocument, writeOpenAPIDocument } from '@di-framework/http';

const result = await generateOpenAPIDocument({
  controllerModules: ['./src/index.ts'],
  configuration: { title: 'My API', version: '1.0.0' },
});

writeOpenAPIDocument(result.document, './openapi.json');
```

统一命令是 `di-framework http openapi generate`; 终端输出 并属于 `@di-framework/cli`。 。 。 .

#### 手动生成

您也可以在程序上使用 `generateOpenAPI` 函数和默认值 `registry`数字 :

```typescript
import registry, { generateOpenAPI } from '@di-framework/http';
import './controllers/MyController'; // Import to trigger registration

const spec = generateOpenAPI(
  {
    title: 'My API',
    version: '1.0.0',
  },
  registry,
);

console.log(JSON.stringify(spec, null, 2));
```

如果你需要全能控制,你就可以将 `registry` 手动 :

```typescript
import registry from '@di-framework/http';

for (const target of registry.getTargets()) {
  // target is the decorated class
  // target[methodName].isEndpoint will be true
  // target[methodName].metadata contains your @Endpoint info
}
```

## API 参考

### `TypedRouter<Args[]>()`

一个代理 `itty-router` 从而可以对类型安全方法进行定义.

-   `Args`: 代表额外参数的一系列类型 `fetch` (例如, `[Env, ExecutionContext]`) (中文(简体) ).

### `json<T>(data: T, init?: ResponseInit)`

一个打字的包装 围绕它的路由器 `json` 帮手.

### `Json<T>` 编号 : `Multipart<T>`

与 `RequestSpec<>` 以声明预期内容类型. `Json<T>` 类型 `req.content` 作为 `T`· ; `Multipart<T>` 键入为 `FormData`多段路线需要通过 `{ multipart: true }` 作为路线方法的第三个参数.

### `@Controller(options?)`

由下列设计者组成:

-   标记一个列入OpenAPI登记册的类别;以及
-   以核心 DI 容器登记类别(与 `@di-framework/core`) (中文(简体) ).

**选项 :** `{ singleton?: boolean; container?: DIContainer }`

### `@Endpoint(metadata)`

附加 OpenAPI 元数据的方法或属性装饰器.

-   `summary`:操作简略.
-   `description`:活字解释.
-   `requestBody`: OpenAPI 请求对象.
-   `responses`: OpenAPI 反应对象.

## 便携式运行时间进口

这个 `wasmcloud` 导出条件选择一个没有文件系统包装的运行时间条目, 文件流,或 OpenAPI 文件生成。 其他便携式捆绑机可导入 `@di-framework/http/portable` 当然 与原生资产组合静态资产 `packageStaticAssets` 构建时的 API , 然后将生成的软件包传递到 `router.static()` 或登记在 `registerStaticAssets`。 。 。 .

本地进口 `@di-framework/http` 保留磁盘服务、包装和 OpenAPI 文件生成. 便携式条目保留路由, 内置的 OpenAPI 生成计划, 包装文本和二进制资产, 有条件的请求, HEAD, 和同样的路径验证.

## 许可证

任何许可 [麻省理工学院](https://npmcn.com/package/LICENSE-MIT) 或者说 [阿帕奇 - 2.0](https://npmcn.com/package/LICENSE-APACHE)随便你.

## 常见问题

### @di-framework/http 是什么？

延长带有 HTTP 特性的 二框架

### 如何安装 @di-framework/http？

在项目目录运行 npm install @di-framework/http，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：typescript（^5）、@di-framework/core（^6）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @di-framework/http 支持 TypeScript 吗？

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

### @di-framework/http 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @di-framework/http 可以商用吗？

@di-framework/http 使用 \(MIT OR Apache-2\.0\) 许可。可在 MIT、Apache-2\.0 中任选其一遵守。选择 MIT 时，宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @di-framework/http 的下载量有多少？

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

### @di-framework/http 还在维护吗？

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

