elysia
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseElysia Developer Guide
Elysia 开发者指南
This skill provides guidelines, patterns, and best practices for working with the Elysia framework in this project.
本技能提供了在本项目中使用Elysia框架的开发规范、模式和最佳实践。
Quick Start
快速入门
For detailed development guidelines, imports, and patterns, please refer to in this skill directory.
references/patterns.md如需了解详细的开发规范、导入规则和模式,请参考本技能目录下的 。
references/patterns.mdCore Philosophy
核心理念
- Pattern-agnostic but feature-based structure recommended
- "1 Elysia instance = 1 controller" principle
- Strong typing with TypeBox for runtime validation
- Centralized error handling and consistent responses
- Production-ready deployment strategies
- 推荐采用不限制模式但基于功能的结构
- 遵循**「1 Elysia实例 = 1个控制器」**原则
- 搭配TypeBox实现强类型运行时校验
- 集中式错误处理和统一的响应格式
- 生产可用的部署策略
Structure, Routing & Controllers
结构、路由与控制器
Essential Organization Patterns
核心组织模式
- App as controller: Treat each instance as the controller for that feature. Do not pass entire class methods directly as handlers. Instead, inline a small handler that calls service functions.
new Elysia({ prefix }) - Feature folders: Use a feature-based structure:
- - Elysia controller (routes, guards, cookies)
src/modules/<feature>/index.ts - - business logic (no HTTP context)
src/modules/<feature>/service.ts - - schemas & types via
src/modules/<feature>/model.ts(TypeBox)t - Keep shared utilities in .
src/utils/*
- Method chaining: Prefer fluent chaining on the Elysia instance for routes, guards, plugins.
- Plugins: Encapsulate cross-cutting concerns in plugins via (e.g., OpenAPI, JWT, CORS).
.use() - Context hygiene: If a service needs request data, keep it in the controller and pass only the relevant fields into the service function.
- 应用即控制器:将每个 实例视为对应功能的控制器。不要直接将整个类方法作为处理程序传入,而是内联一个调用服务函数的小型处理程序。
new Elysia({ prefix }) - 功能文件夹:采用基于功能的结构:
- - Elysia控制器(路由、守卫、Cookie处理)
src/modules/<feature>/index.ts - - 业务逻辑(无HTTP上下文)
src/modules/<feature>/service.ts - - 基于
src/modules/<feature>/model.ts(TypeBox)定义的 schema 和类型t - 共享工具类放在 目录下。
src/utils/*
- 方法链式调用:推荐在Elysia实例上使用流式链式调用定义路由、守卫、插件。
- 插件:通过封装跨领域关注点(例如OpenAPI、JWT、CORS)。
.use() - 上下文纯净性:如果服务需要请求数据,在控制器层处理,仅将相关字段传入服务函数。
Feature Scaffolding Pattern
功能脚手架模式
When scaffolding a feature, generate:
- with
model.tsschemas and exportedt.Object(...)aliases viatype.typeof schema.static - with pure functions (or an
service.tsof statics when no instance state is needed).abstract class - that mounts the Elysia routes, applies
index.tswith shared validation, and returns typed responses.guard()
搭建新功能时,生成以下文件:
- :包含
model.tsschema,通过t.Object(...)导出typeof schema.static别名。type - :包含纯函数(无需实例状态时也可以是静态方法的抽象类)。
service.ts - :挂载Elysia路由,应用共享校验的
index.ts,返回带类型的响应。guard()
Validation, Schemas & Types
校验、Schema与类型
Runtime Validation + Static Types
运行时校验 + 静态类型
- Use to define Body, Query, Params, Headers, Cookie, and Response schemas.
import { t } from 'elysia' - Derive TS types from and export them (e.g.,
typeof schema.static).export type SignInBody = typeof signInBody.static - Apply shared validation with . If combining guards, consider
.guard({ ... })to keep them independent.schema: 'standalone' - Validate files by content: use (magic number) when using standard schema systems.
fileType - Ensure response schemas are present for 2xx and error variants for strong end-to-end typing.
- 使用定义Body、Query、Params、Headers、Cookie和Response schema。
import { t } from 'elysia' - 从派生TS类型并导出(例如
typeof schema.static)。export type SignInBody = typeof signInBody.static - 通过应用共享校验。如果需要组合多个守卫,可使用
.guard({ ... })保持其独立性。schema: 'standalone' - 校验文件内容:使用标准schema系统时通过(魔数)校验。
fileType - 确保为2xx响应和错误变体都定义响应schema,实现强类型端到端校验。
Handler Schema Guidelines
处理程序Schema规范
When generating handlers:
- Include the 3rd argument schema object with .
body/query/params/headers/cookie/response - Don't parse body for GET/HEAD (Elysia follows HTTP spec).
- Provide examples with ,
t.Object,t.Array,t.Union, file schemas, and showt.Literalfor shared query/headers.guard()
生成处理程序时:
- 第三个参数传入包含的schema对象。
body/query/params/headers/cookie/response - 不要为GET/HEAD请求解析body(Elysia遵循HTTP规范)。
- 提供、
t.Object、t.Array、t.Union、文件schema的示例,展示t.Literal用于共享query/headers的用法。guard()
Error Handling & Response Shape
错误处理与响应格式
Centralized Error Management
集中式错误管理
- Use on the app to map framework and custom errors to a uniform JSON shape (e.g.,
.onError(({ code, error, path, request }) => { ... })).{ ok: false, error: { code, message, details } } - Prefer for error control flow that
throw status(code, messageOrPayload)can catch. Note:onErrorwon't be caught byreturn status(...).onError - Validation errors: normalize them to a predictable JSON (array of issues) while hiding sensitive internals in production.
- Include correlation ids (e.g., ) and log within
x-request-id. Avoid leaking stack traces in production.onError - For success responses, optionally wrap in for uniformity.
{ ok: true, data }
- 在应用上使用将框架错误和自定义错误映射为统一JSON格式(例如
.onError(({ code, error, path, request }) => { ... }))。{ ok: false, error: { code, message, details } } - 错误控制流优先使用,这样可以被
throw status(code, messageOrPayload)捕获。注意:onError不会被return status(...)捕获。onError - 校验错误:将其格式化为可预测的JSON(问题数组),生产环境隐藏敏感内部信息。
- 在中包含关联ID(例如
onError)并打日志。生产环境避免泄露堆栈信息。x-request-id - 成功响应可选择包裹为格式保持统一性。
{ ok: true, data }
Error Plugin Structure
错误插件结构
When generating code, create:
- that installs
src/plugins/error.ts..onError(...) - Optionally to log in
src/plugins/logging.ts&onResponse.onError
生成代码时创建:
- :注册
src/plugins/error.ts逻辑。.onError(...) - 可选的:在
src/plugins/logging.ts和onResponse中打日志。onError
OpenAPI, Auth & Cross-cutting
OpenAPI、鉴权与跨领域功能
OpenAPI
OpenAPI
- Add plugin and expose docs route (Scalar UI).
@elysiajs/openapi - Keep response schemas accurate - OpenAPI derives from them.
- If building SDKs, ensure routes are fully typed and examples provided.
- 添加插件,暴露文档路由(Scalar UI)。
@elysiajs/openapi - 保持响应schema准确,OpenAPI会基于其生成文档。
- 如果需要构建SDK,确保路由全类型覆盖并提供示例。
Auth
鉴权
- Use for JWT signing/verification, or integrate with your auth of choice.
@elysiajs/jwt - Keep auth in a plugin that decorates context with after verification.
user - Protect routes via and verify bearer tokens before handlers.
.guard({ headers: t.Object({ authorization: t.String() }) })
- 使用做JWT签名/校验,或集成你选择的其他鉴权方案。
@elysiajs/jwt - 将鉴权逻辑封装在插件中,校验通过后为上下文添加属性。
user - 通过保护路由,在处理程序执行前校验Bearer令牌。
.guard({ headers: t.Object({ authorization: t.String() }) })
Cross-cutting Plugins
跨领域插件
- Install where needed.
@elysiajs/cors - Consider and
@elysiajs/server-timingfor observability.@elysiajs/opentelemetry
When scaffolding, generate , , and wire them in .
src/plugins/openapi.tssrc/plugins/auth.tssrc/app.ts- 按需安装。
@elysiajs/cors - 可考虑使用和
@elysiajs/server-timing实现可观测性。@elysiajs/opentelemetry
搭建脚手架时生成、,并在中引入注册。
src/plugins/openapi.tssrc/plugins/auth.tssrc/app.tsDeploy, Performance & Docker
部署、性能与Docker
Production Deployment
生产部署
- Cluster mode for multi-core: use a small launcher () that forks workers and imports
index.tsper worker.server.ts - Prefer building with bundlers like Vite or esbuild for production deployments.
- If compiling interferes with tracing (OpenTelemetry), avoid or mark instrumented modules as
--minify.--external - Accept (with fallback) and bind
process.env.PORTfor PaaS.0.0.0.0
- 多核场景使用集群模式:使用小型启动文件()fork工作进程,每个工作进程导入
index.ts。server.ts - 生产部署优先使用Vite或esbuild等打包工具构建。
- 如果编译影响链路追踪(OpenTelemetry),避免使用或将被埋点的模块标记为
--minify。--external - 读取(带默认值),绑定
process.env.PORT适配PaaS平台。0.0.0.0
Docker
Docker
- Build stage: use Node.js base image with pnpm.
- Runtime: distroless base, copy binary, .
CMD ["./server"]
- 构建阶段:使用带pnpm的Node.js基础镜像。
- 运行时:使用distroless基础镜像,复制二进制文件,。
CMD ["./server"]
Deployment Scaffolding
部署脚手架
When generating a deploy scaffold, include:
- (cluster launcher),
src/index.ts(app),src/server.ts(multi-stage), and build scripts.Dockerfile
生成部署脚手架时包含:
- (集群启动文件)、
src/index.ts(应用入口)、src/server.ts(多阶段构建)和构建脚本。Dockerfile
Testing
测试
Unit Tests
单元测试
- Use .
vitest - Import the app and use to assert status/body/headers.
app.handle(new Request(url, options)) - For service tests, call pure functions directly.
- 使用。
vitest - 导入应用实例,使用断言状态码/响应体/响应头。
app.handle(new Request(url, options)) - 服务测试直接调用纯函数即可。
Test Examples to Include
测试示例需包含
- Simple GET test returning text.
- POST with validation (both valid and invalid paths).
body - Authenticated route example using a mocked header.
Authorization - Prefer small, focused tests per route and per service.
- 简单GET请求返回文本的测试。
- 带校验的POST请求测试(合法和非法路径都覆盖)。
body - 使用模拟头的鉴权路由测试。
Authorization - 每个路由和每个服务优先编写小型、聚焦的测试用例。
Quick Utilities
快速工具
Common Patterns
常用模式
- App context: use and
.state()to add version info, helpers, etc., then read from.decorate().{ store, getDate } - WebSocket endpoints via for simple real-time APIs.
.ws() - Custom body parser with for special content types.
.onParse()
- 应用上下文:使用和
.state()添加版本信息、工具方法等,后续从.decorate()中读取。{ store, getDate } - 通过定义WebSocket端点,实现简单的实时API。
.ws() - 通过自定义body解析器,处理特殊的Content-Type。
.onParse()
Validation Checklist
校验清单
Before finishing a task involving Elysia:
- Feature structure follows ,
model.ts,service.tspattern.index.ts - All handlers have proper schema definitions (body/query/params/response).
- Error handling uses centralized plugin.
.onError() - Response schemas are defined for OpenAPI generation.
- Tests use pattern.
app.handle(new Request(...)) - Run type checks () and tests (
pnpm run typecheck).pnpm run test
For detailed patterns and code examples, see .
references/patterns.md完成涉及Elysia的任务前,请检查:
- 功能结构遵循、
model.ts、service.ts模式。index.ts - 所有处理程序都有正确的schema定义(body/query/params/response)。
- 错误处理使用集中式插件。
.onError() - 已定义响应schema用于OpenAPI生成。
- 测试使用模式。
app.handle(new Request(...)) - 运行类型检查()和测试(
pnpm run typecheck)。pnpm run test
如需了解详细模式和代码示例,请查看。
references/patterns.md