@dunx/http

中文文档
3.10.6发布于 2026/10/30MITTypeScriptES Module构建来源已验证近 30 天下载 5054

Bun.serve adapter for the dunx framework: controllers, middleware and WebSocket gateways

原始使用文档
文档目录6 节
  1. Install
  2. Usage
  3. What is here
  4. Subpaths
  5. Notes
  6. License

@dunx/http

Class-based controllers and WebSocket gateways for dunx, served by Bun.serve with standard decorators. There is no JavaScript router: Bun's built-in routes handles path parameters and HTTP methods natively.

HTTP and WebSockets share one listen(), one server and one port, without express, ws or socket.io.

Install

bun add @dunx/http @dunx/core @dunx/transform

Add preload = ["@dunx/transform/preload"] to bunfig.toml for constructor injection, once at the top level and once under [test].

Usage

import { inject, Module } from '@dunx/core';
import { Controller, Get, HttpFactory, Post, type Input } from '@dunx/http';
import { z } from 'zod'; // or Valibot, or ArkType, or none at all

const createUser = { body: z.object({ name: z.string() }) } as const;
const oneUser = { params: z.object({ id: z.coerce.number() }) } as const;

@Controller('users')
export class UsersController {
  readonly #users = inject(UsersService);

  @Get('/')
  list() {
    return this.#users.findAll(); // plain values become Response.json()
  }

  @Get('/:id', oneUser)
  one(input: Input<typeof oneUser>) {
    return this.#users.find(input.params.id); // a number, already validated
  }

  @Post('/', createUser)
  create(input: Input<typeof createUser>) {
    return this.#users.create(input.body.name); // 201, no Response.json()
  }
}

@Module({ controllers: [UsersController], providers: [UsersService] })
export class UsersModule {}

const app = await HttpFactory.create(AppModule);
app.enableShutdownHooks();
await app.listen(3000);

What is here

Each row links to the guide that covers it.

AreaWhat it coversGuide
Controllers and routingVerb decorators, path params, prefixes, status codesControllers
Typed inputbody, query, params over Standard SchemaValidation
Middleware and guardsOne extension point, @UseGuards, @Roles, @PublicMiddleware and guards
WebSocket gateways@Gateway, handlers, PubSub, multi-node relayWebSockets
Server-sent events@Sse, SseStream, framing, heartbeats, Last-Event-IDControllers
Request loggingOne structured entry per request, on by defaultLogging
Trace contextW3C traceparent adopted and propagated, on by defaultLogging
SpansA SERVER span per request and a CLIENT span per call, with OtelModuleTracing
MetricsPer-route counts and timings, off by defaultMetrics
Health and draining/health/live, /health/ready, readiness during a rolloutHealth checks
Throttling@Throttle, @SkipThrottle, memory and Redis countersMiddleware and guards
Outbound resilienceHttpRetryClassifier: which statuses retry, and Retry-AfterResilience
Static filesBun.file behind a mount, with a cache policyDeployment
Compressionzstd, brotli and gzip on Bun's own compressorsDeployment
RPCprotobuf over Connect and gRPC-Web, as middlewareRPC

Subpaths

SubpathContains
@dunx/httpEverything above
@dunx/http/clientThe outbound half: HttpService, retry with backoff, HttpModule
@dunx/http/connectprotobuf services over Connect and gRPC-Web, mounted as middleware
@dunx/http/internalThe framework's own plumbing. No stability promise

@dunx/http/internal is for dunx's own packages: @dunx/dashboard, @dunx/mcp and @dunx/openapi. Do not import it from an app, since it can change in any release.

Notes

  • Routes are found at boot, including those inherited from a base class, so a subclass of an abstract controller serves its parent's @Get methods too.
  • Two handlers for the same method and path fail at boot, and the error names both. Bun would otherwise keep one of them without saying so.
  • A handler can return a Response, any JSON-serialisable value, or undefined for a 204.
  • Authorize and gate() protect admin pages. They receive the raw request and answer 404 when access is refused, or send a Response you return as it is, such as a sign-in page. @dunx/dashboard and @dunx/openapi both accept one, so you write the access rule once.
  • Schemas, parsers and status codes are worked out once at boot. Handling a request does no metadata lookups.
  • Every request joins the caller's W3C trace (traceparent). Its log lines carry traceId, spanId, parentSpanId and traceFlags, and the response carries a traceresponse header. requestLogging: { trace: false } turns both off. { traceResponse: false } keeps the trace fields and drops only the header, which saves about 500 ns a request. There is no separate correlation id.
  • metrics: true adds request counts and a latency histogram per route, for about 35 ns a request.
  • @dunx/http/connect serves Connect and gRPC-Web, but not native gRPC. Native gRPC sends its status in an HTTP trailer, which Bun.serve cannot send, so a request with content-type: application/grpc gets a 415 explaining why. @connectrpc/connect and @bufbuild/protobuf are optional peer dependencies, and you keep your own .proto toolchain. ThrottleGuard applies to RPC paths as well.

License

MIT

版本与发布记录

@dunx/http 共发布 83 个版本,首次发布于 2026/08/02;过去 12 个月发布了 83 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.10.6latest2026/10/3014 天前
3.10.52026/10/2222 天前
3.10.42026/10/2024 天前
3.10.32026/10/1430 天前
3.10.22026/10/081 个月前
3.10.12026/09/261 个月前

关于 @dunx/http 的常见问题

@dunx/http 是什么?

Bun.serve adapter for the dunx framework: controllers, middleware and WebSocket gateways

如何安装 @dunx/http?

在项目目录运行 npm install @dunx/http,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@dunx/core(^3.10.6)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dunx/http 支持 TypeScript 吗?

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

@dunx/http 支持 ESM 还是 CommonJS?

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

@dunx/http 可以商用吗?

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

@dunx/http 的下载量有多少?

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

@dunx/http 还在维护吗?

最新版本 3.10.6 发布于 2026/10/30(14 天前);至今共发布 83 个版本,其中过去 12 个月发布了 83 个;首次发布于 2026/08/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。