Explorar o código

统一api定义

yourname hai 6 meses
pai
achega
30e8f3f182
Modificáronse 3 ficheiros con 105 adicións e 150 borrados
  1. 3 3
      src/client/app.tsx
  2. 14 147
      src/server/api/base.ts
  3. 88 0
      src/server/api/migration.ts

+ 3 - 3
src/client/app.tsx

@@ -1,11 +1,11 @@
 import { createBrowserRouter, RouterProvider } from 'react-router-dom'
 import { hc } from 'hono/client'
 import { useQuery } from '@tanstack/react-query'
-import type { AppType } from '../server/api/base'
+import type { BaseRoutes } from '../server/api/base'
 import type { UserRoutes } from '../server/api/user'
 
-const client = hc<AppType>('/api')
-const userClient = hc<UserRoutes['createUser']>('/api/user')
+const client = hc<BaseRoutes>('/api')
+const userClient = hc<UserRoutes['createUser']>('/api')
 
 const Home = () => {
   return (

+ 14 - 147
src/server/api/base.ts

@@ -1,35 +1,8 @@
 import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
 import { z } from 'zod'
-import { AppDataSource } from '../data-source'
-import { HTTPException } from 'hono/http-exception';
-
-interface Migration {
-  name: string;
-  timestamp: number;
-}
-
-interface MigrationResult {
-  migrations: Migration[];
-}
-
-interface ExecutedMigration {
-  name: string;
-  timestamp: string;
-}
-
-interface PendingMigration {
-  name: string;
-  status: string;
-}
-
-interface MigrationHistory {
-  executed: ExecutedMigration[];
-  pending: PendingMigration[];
-}
 
 const app = new OpenAPIHono()
 
-// Base route
 const QuerySchema = z.object({
   name: z.string().optional().openapi({
     param: {
@@ -46,24 +19,16 @@ const ResponseSchema = z.object({
   })
 })
 
-const MigrationResponseSchema = z.object({
-  success: z.boolean(),
-  message: z.string(),
-  migrations: z.array(z.string()).optional()
-})
-
-const MigrationHistoryResponseSchema = z.object({
-  executed: z.array(z.object({
-    name: z.string(),
-    timestamp: z.string()
-  })),
-  pending: z.array(z.object({
-    name: z.string(),
-    status: z.string()
-  }))
+const ErrorSchema = z.object({
+  code: z.number().openapi({
+    example: 400,
+  }),
+  message: z.string().openapi({
+    example: 'Bad Request',
+  }),
 })
 
-const baseRoute = createRoute({
+const route = createRoute({
   method: 'get',
   path: '/',
   request: {
@@ -79,118 +44,20 @@ const baseRoute = createRoute({
       description: 'Successful response'
     },
     400: {
-      description: 'Invalid request'
-    }
-  }
-})
-
-const runMigrationRoute = createRoute({
-  method: 'post',
-  path: '/migrations/run',
-  responses: {
-    200: {
-      content: {
-        'application/json': {
-          schema: MigrationResponseSchema
-        }
-      },
-      description: 'Migrations executed successfully'
-    },
-    500: {
-      description: 'Migration failed'
-    }
-  }
-})
-
-const revertMigrationRoute = createRoute({
-  method: 'post',
-  path: '/migrations/revert',
-  responses: {
-    200: {
       content: {
         'application/json': {
-          schema: MigrationResponseSchema
-        }
+          schema: ErrorSchema,
+        },
       },
-      description: 'Migration reverted successfully'
-    },
-    500: {
-      description: 'Revert failed'
+      description: 'Invalid request'
     }
   }
 })
 
-app.openapi(baseRoute, (c) => {
+const baseRoutes = app.openapi(route, (c) => {
   const { name } = c.req.valid('query')
-  return c.json({ message: `Hello from API${name ? `, ${name}` : ''}` })
-})
-
-app.openapi(runMigrationRoute, async (c) => {
-  try {
-    const migrations = await AppDataSource.runMigrations()
-    return c.json({
-      success: true,
-      message: 'Migrations executed successfully',
-      migrations: migrations.map((m: Migration) => m.name)
-    })
-  } catch (error) {
-    throw error
-  }
-})
-
-app.openapi(revertMigrationRoute, async (c) => {
-  try {
-    await AppDataSource.undoLastMigration()
-    const migrations = await AppDataSource.showMigrations()
-    return c.json({
-      success: true,
-      message: 'Migration reverted successfully',
-      migrations: migrations
-    })
-  } catch (error) {
-    throw error
-  }
-})
-
-const migrationHistoryRoute = createRoute({
-  method: 'get',
-  path: '/migrations/history',
-  responses: {
-    200: {
-      content: {
-        'application/json': {
-          schema: MigrationHistoryResponseSchema
-        }
-      },
-      description: 'Migration history retrieved successfully'
-    },
-    500: {
-      description: 'Failed to get migration history'
-    }
-  }
+  return c.json({ message: `Hello from API${name ? `, ${name}` : ''}` }, 200)
 })
 
-// app.openapi(migrationHistoryRoute, async (c) => {
-//   try {
-//     // Get executed migrations from database
-//     // const executedMigrations = await AppDataSource.query('SELECT * FROM migrations')
-    
-//     // Get pending migrations from TypeORM
-//     const pendingMigrations = await AppDataSource.showMigrations()
-    
-//     const result: MigrationHistory = {
-//       // executed: executedMigrations.map((m: any) => ({
-//       //   name: m.name,
-//       //   timestamp: new Date(m.timestamp).toISOString()
-//       // })),
-//       pending: pendingMigrations
-//     }
-    
-//     return c.json(result)
-//   } catch (error) {
-//     throw new HTTPException(500,{cause: error})
-//   }
-// })
-
 export default app
-export type AppType = typeof app
+export type BaseRoutes = typeof baseRoutes

+ 88 - 0
src/server/api/migration.ts

@@ -0,0 +1,88 @@
+import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
+import { z } from 'zod'
+import { AppDataSource } from '../data-source'
+import { HTTPException } from 'hono/http-exception';
+import { AuthContext, authMiddleware } from '../middleware/auth.middleware';
+
+interface Migration {
+  name: string;
+  timestamp: number;
+}
+
+const app = new OpenAPIHono<AuthContext>()
+
+const MigrationResponseSchema = z.object({
+  success: z.boolean(),
+  message: z.string(),
+  migrations: z.array(z.string()).optional()
+})
+
+const runMigrationRoute = createRoute({
+  method: 'post',
+  path: '/migrations/run',
+  middleware: authMiddleware,
+  responses: {
+    200: {
+      content: {
+        'application/json': {
+          schema: MigrationResponseSchema
+        }
+      },
+      description: 'Migrations executed successfully'
+    },
+    500: {
+      description: 'Migration failed'
+    }
+  }
+})
+
+const revertMigrationRoute = createRoute({
+  method: 'post',
+  path: '/migrations/revert',
+  middleware: authMiddleware,
+  responses: {
+    200: {
+      content: {
+        'application/json': {
+          schema: MigrationResponseSchema
+        }
+      },
+      description: 'Migration reverted successfully'
+    },
+    500: {
+      description: 'Revert failed'
+    }
+  }
+})
+
+app.openapi(runMigrationRoute, async (c) => {
+  try {
+    const migrations = await AppDataSource.runMigrations()
+    return c.json({
+      success: true,
+      message: 'Migrations executed successfully',
+      migrations: migrations.map((m: Migration) => m.name)
+    })
+  } catch (error) {
+    throw error
+  }
+})
+
+app.openapi(revertMigrationRoute, async (c) => {
+  try {
+    await AppDataSource.undoLastMigration()
+    const migrations = await AppDataSource.showMigrations()
+    return c.json({
+      success: true,
+      message: 'Migration reverted successfully',
+      migrations: migrations
+    })
+  } catch (error) {
+    throw error
+  }
+})
+
+
+
+export default app
+export type AppType = typeof app