api-route-endpoint
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Route/Endpoint Skill
API路由/端点开发规范
Follow existing Hono patterns in apps/api when creating or updating endpoints.
在创建或更新端点时,请遵循apps/api目录中已有的Hono代码模式。
Workflow
工作流程
- Identify the feature folder under and create or update the three files:
apps/api/src/routes- (route wiring)
routes/<feature>/<feature>.index.ts - (handlers)
routes/<feature>/<feature>.handler.ts - (Zod schemas)
routes/<feature>/<feature>.schema.ts
- Use for route modules and
createRouter()for handlers.createHandlers() - Use from
validate()with Zod schemas.apps/api/src/lib/validator.ts - Use for database access.
initializePrisma(c.env.DATABASE_URL) - Return JSON with the standard response structure (see references).
- Wire middleware for auth/roles where needed.
- Register the route in if it is a new top-level group.
apps/api/src/routes/index.ts
- 在下找到对应的功能文件夹,创建或更新以下三个文件:
apps/api/src/routes- (路由配置)
routes/<feature>/<feature>.index.ts - (请求处理器)
routes/<feature>/<feature>.handler.ts - (Zod校验模式)
routes/<feature>/<feature>.schema.ts
- 使用创建路由模块,使用
createRouter()定义请求处理器。createHandlers() - 结合Zod模式,使用中的
apps/api/src/lib/validator.ts方法进行校验。validate() - 使用进行数据库访问。
initializePrisma(c.env.DATABASE_URL) - 按照标准响应结构返回JSON数据(参考相关文档)。
- 根据需要配置认证/角色权限中间件。
- 如果是新增的顶级路由组,需要在中注册该路由。
apps/api/src/routes/index.ts
Required patterns
必须遵循的规范
- Route wiring: use ,
.get,.post,.putwith spread handler arrays:.delete.route.get('/', ...getItems) - Validation: as the first handlers in
validate('param' | 'query' | 'json', schema).createHandlers - Handler response: return .
c.json({ meta: { code, message }, data: { ... } }, code) - Errors: map Prisma errors to status codes where appropriate; fall through to app error handler.
- 路由配置:使用、
.get、.post、.put方法,并传入展开的处理器数组,例如:.delete。route.get('/', ...getItems) - 校验规则:在的第一个处理器位置使用
createHandlers。validate('param' | 'query' | 'json', schema) - 处理器响应:返回格式的数据。
c.json({ meta: { code, message }, data: { ... } }, code) - 错误处理:将Prisma错误映射为对应的状态码;未匹配的错误交由应用全局错误处理器处理。
Middleware
中间件
- Use for authenticated routes.
requireAuth - Use for admin-only routes.
requireAdminRole
- 对于需要认证的路由,使用中间件。
requireAuth - 对于仅管理员可访问的路由,使用中间件。
requireAdminRole
Response structure
响应结构
- Always return .
{ meta: { code, message }, data: { ... } } - For errors with no payload, return .
data: {}
- 必须返回格式的数据。
{ meta: { code, message }, data: { ... } } - 无返回数据的错误响应,需返回。
data: {}
References
参考文档
- See for concrete file layouts, schema patterns, and response examples.
references/api-route-patterns.md
- 具体的文件结构、模式示例和响应示例,请参考。
references/api-route-patterns.md