|
|
@@ -0,0 +1,76 @@
|
|
|
+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 { PostSchema } from '@/server/modules/posts/post.entity';
|
|
|
+import { ErrorSchema } from '@/server/utils/errorHandler';
|
|
|
+
|
|
|
+// 查询参数Schema
|
|
|
+const QuerySchema = z.object({
|
|
|
+ page: z.coerce.number().int().positive().default(1).openapi({
|
|
|
+ example: 1,
|
|
|
+ description: '页码'
|
|
|
+ }),
|
|
|
+ pageSize: z.coerce.number().int().positive().default(10).openapi({
|
|
|
+ example: 10,
|
|
|
+ description: '每页条数'
|
|
|
+ })
|
|
|
+});
|
|
|
+
|
|
|
+// 响应Schema
|
|
|
+const PopularPostsResponse = z.object({
|
|
|
+ data: z.array(PostSchema),
|
|
|
+ pagination: z.object({
|
|
|
+ total: z.number().openapi({ example: 100, description: '总记录数' }),
|
|
|
+ current: z.number().openapi({ example: 1, description: '当前页码' }),
|
|
|
+ pageSize: z.number().openapi({ example: 10, description: '每页数量' })
|
|
|
+ })
|
|
|
+});
|
|
|
+
|
|
|
+// 路由定义
|
|
|
+const routeDef = createRoute({
|
|
|
+ method: 'get',
|
|
|
+ path: '/featured',
|
|
|
+ // 不添加authMiddleware,确保公开访问
|
|
|
+ request: {
|
|
|
+ query: QuerySchema
|
|
|
+ },
|
|
|
+ responses: {
|
|
|
+ 200: {
|
|
|
+ description: '成功获取热门帖子列表',
|
|
|
+ content: { 'application/json': { schema: PopularPostsResponse } }
|
|
|
+ },
|
|
|
+ 400: {
|
|
|
+ description: '请求参数错误',
|
|
|
+ content: { 'application/json': { schema: ErrorSchema } }
|
|
|
+ },
|
|
|
+ 500: {
|
|
|
+ description: '服务器错误',
|
|
|
+ content: { 'application/json': { schema: ErrorSchema } }
|
|
|
+ }
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+// 路由实现
|
|
|
+const app = new OpenAPIHono().openapi(routeDef, async (c) => {
|
|
|
+ try {
|
|
|
+ const { page, pageSize } = c.req.valid('query');
|
|
|
+ const postService = new PostService(AppDataSource);
|
|
|
+
|
|
|
+ const [posts, total] = await postService.getPopularPosts(page, pageSize);
|
|
|
+
|
|
|
+ return c.json({
|
|
|
+ data: posts,
|
|
|
+ pagination: {
|
|
|
+ total,
|
|
|
+ current: page,
|
|
|
+ pageSize
|
|
|
+ }
|
|
|
+ }, 200);
|
|
|
+ } catch (error) {
|
|
|
+ const { code = 500, message = '获取热门帖子失败' } = error as Error & { code?: number };
|
|
|
+ return c.json({ code, message }, code as unknown as 400 | 500);
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+export default app;
|