| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { AuthContext } from '@d8d/shared-types';
- import { authMiddleware } from '@d8d/shared-utils';
- import { AppDataSource } from '@d8d/shared-utils';
- import { AuthService } from '../services';
- import { UserService } from '@d8d/user-module';
- import { ErrorSchema } from '@d8d/shared-utils';
- import { SuccessSchema } from '../schemas';
- // 定义路由
- const routeDef = createRoute({
- method: 'post',
- path: '/logout',
- security: [{ Bearer: [] }],
- middleware: [authMiddleware],
- responses: {
- 200: {
- description: '登出成功',
- content: {
- 'application/json': {
- schema: SuccessSchema
- }
- }
- },
- 401: {
- description: '未授权',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- // 在路由处理函数内部初始化服务
- const userService = new UserService(AppDataSource);
- const authService = new AuthService(userService);
- const token = c.get('token');
- const decoded = authService.verifyToken(token);
- if (!decoded) {
- return c.json({ code: 401, message: '未授权' }, 401);
- }
- await authService.logout(token);
- return c.json({ message: '登出成功' }, 200);
- } catch (error) {
- console.error('登出失败:', error);
- return c.json({ code: 500, message: '登出失败' }, 500);
- }
- });
- export default app;
|