|
|
@@ -307,9 +307,7 @@ export * from './channel-crud.routes';
|
|
|
|
|
|
### 4.3 自定义路由响应规范
|
|
|
|
|
|
-**重要**: 自定义路由(非CRUD路由)在返回响应前**必须使用 `parseWithAwait`** 验证和转换数据。
|
|
|
-
|
|
|
-#### 使用 createRoute 定义路由
|
|
|
+**重要**: 自定义路由(非CRUD路由)必须使用 `createRoute` 定义,并在返回响应前使用 `parseWithAwait` 验证和转换数据。
|
|
|
|
|
|
**完整示例**:
|
|
|
```typescript
|
|
|
@@ -375,39 +373,10 @@ channelCustomRoutes.openapi(createChannelRoute, async (c) => {
|
|
|
});
|
|
|
```
|
|
|
|
|
|
-#### 不使用 createRoute 的简化写法
|
|
|
-
|
|
|
-如果路由不需要完整的 OpenAPI 文档定义,可以使用简化写法:
|
|
|
-
|
|
|
-```typescript
|
|
|
-import { parseWithAwait, createZodErrorResponse } from '@d8d/shared-utils';
|
|
|
-import { z } from '@hono/zod-openapi';
|
|
|
-import { ChannelSchema } from '../schemas/channel.schema';
|
|
|
-
|
|
|
-// 自定义路由
|
|
|
-channelCustomRoutes.get('/statistics/:id', async (c) => {
|
|
|
- try {
|
|
|
- const id = c.req.param('id');
|
|
|
- const channelService = new ChannelService(AppDataSource);
|
|
|
- const result = await channelService.getStatistics(Number(id));
|
|
|
-
|
|
|
- // ✅ 必须:使用 parseWithAwait 验证和转换响应数据
|
|
|
- const validatedResult = await parseWithAwait(ChannelSchema, result);
|
|
|
- return c.json(validatedResult, 200);
|
|
|
- } catch (error) {
|
|
|
- if (error instanceof z.ZodError) {
|
|
|
- // ✅ 推荐:使用 createZodErrorResponse 处理Zod验证错误
|
|
|
- return c.json(createZodErrorResponse(error), 400);
|
|
|
- }
|
|
|
- return c.json({ code: 500, message: error.message }, 500);
|
|
|
- }
|
|
|
-});
|
|
|
-```
|
|
|
-
|
|
|
#### 数组响应处理
|
|
|
|
|
|
```typescript
|
|
|
-// 处理数组数据
|
|
|
+// 处理数组数据 - 使用 Promise.all 批量验证
|
|
|
const validatedData = await Promise.all(
|
|
|
result.data.map(item => parseWithAwait(ChannelSchema, item))
|
|
|
);
|
|
|
@@ -421,6 +390,7 @@ return c.json({ data: validatedData, total: result.total }, 200);
|
|
|
- **其他错误使用 `ErrorSchema`**: 401, 404, 500 等使用简单的错误格式
|
|
|
|
|
|
**代码实现**:
|
|
|
+- **必须使用 `createRoute`**: 所有自定义路由必须使用 `createRoute` 定义
|
|
|
- **必须使用 `parseWithAwait`**: 所有自定义路由返回前必须验证数据
|
|
|
- **捕获 ZodError**: 在catch块中处理 `z.ZodError` 异常
|
|
|
- **使用 `createZodErrorResponse`**: 提供统一的Zod错误响应格式
|
|
|
@@ -432,6 +402,7 @@ return c.json({ data: validatedData, total: result.total }, 200);
|
|
|
- **使用 `AuthContext` 泛型**: 提供类型安全的认证上下文
|
|
|
- **路由聚合**: 分别定义自定义路由和CRUD路由,然后聚合
|
|
|
- **不设置 `basePath`**: 在聚合路由时处理路径
|
|
|
+- **自定义路由必须使用 `createRoute`**: 所有自定义路由必须使用 `createRoute` 定义
|
|
|
- **自定义路由必须使用 `parseWithAwait`**: 验证响应数据符合Schema定义
|
|
|
- **400响应使用 `ZodErrorSchema`**: 因为使用 `createZodErrorResponse` 返回详细验证错误
|
|
|
- **其他错误使用 `ErrorSchema`**: 401, 404, 500 等使用简单错误格式
|