|
|
@@ -0,0 +1,72 @@
|
|
|
+import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
|
|
|
+import { z } from '@hono/zod-openapi';
|
|
|
+import { AppDataSource } from '@/server/data-source';
|
|
|
+import { PostService } from '@/server/modules/posts/post.service';
|
|
|
+import { UpdatePostDto, PostSchema } from '@/server/modules/posts/post.entity';
|
|
|
+import { AuthContext } from '@/server/types/context';
|
|
|
+import { authMiddleware } from '@/server/middleware/auth.middleware';
|
|
|
+import { ErrorSchema } from '@/server/utils/errorHandler';
|
|
|
+
|
|
|
+// 参数Schema
|
|
|
+const ParamsSchema = z.object({
|
|
|
+ id: z.coerce.number().int().positive().openapi({
|
|
|
+ param: { name: 'id', in: 'path' },
|
|
|
+ example: 1,
|
|
|
+ description: '帖子ID'
|
|
|
+ })
|
|
|
+});
|
|
|
+
|
|
|
+// 路由定义
|
|
|
+const routeDef = createRoute({
|
|
|
+ method: 'put',
|
|
|
+ path: '/{id}',
|
|
|
+ middleware: [authMiddleware],
|
|
|
+ request: {
|
|
|
+ params: ParamsSchema,
|
|
|
+ body: {
|
|
|
+ content: {
|
|
|
+ 'application/json': { schema: UpdatePostDto }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ },
|
|
|
+ responses: {
|
|
|
+ 200: {
|
|
|
+ description: '成功更新帖子',
|
|
|
+ content: { 'application/json': { schema: PostSchema } }
|
|
|
+ },
|
|
|
+ 400: {
|
|
|
+ description: '请求参数错误',
|
|
|
+ content: { 'application/json': { schema: ErrorSchema } }
|
|
|
+ },
|
|
|
+ 404: {
|
|
|
+ description: '帖子不存在或没有权限',
|
|
|
+ content: { 'application/json': { schema: ErrorSchema } }
|
|
|
+ },
|
|
|
+ 500: {
|
|
|
+ description: '服务器错误',
|
|
|
+ content: { 'application/json': { schema: ErrorSchema } }
|
|
|
+ }
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+// 路由实现
|
|
|
+const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
|
|
|
+ try {
|
|
|
+ const { id } = c.req.valid('param');
|
|
|
+ const data = await c.req.json();
|
|
|
+ const user = c.get('user');
|
|
|
+ const postService = new PostService(AppDataSource);
|
|
|
+
|
|
|
+ const result = await postService.updatePost(id, user.id, data);
|
|
|
+ if (!result) {
|
|
|
+ return c.json({ code: 404, message: '帖子不存在或没有权限' }, 404);
|
|
|
+ }
|
|
|
+
|
|
|
+ return c.json(result, 200);
|
|
|
+ } catch (error) {
|
|
|
+ const { code = 500, message = '更新帖子失败' } = error as Error & { code?: number };
|
|
|
+ return c.json({ code, message }, code as unknown as 400 | 404 | 500);
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+export default app;
|