logout.route.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi';
  3. import { AuthContext } from '@d8d/shared-types';
  4. import { authMiddleware } from '@d8d/shared-utils';
  5. import { AppDataSource } from '@d8d/shared-utils';
  6. import { AuthService } from '../services';
  7. import { UserService } from '@d8d/user-module';
  8. import { ErrorSchema } from '@d8d/shared-utils';
  9. import { SuccessSchema } from '../schemas';
  10. // 定义路由
  11. const routeDef = createRoute({
  12. method: 'post',
  13. path: '/logout',
  14. security: [{ Bearer: [] }],
  15. middleware: [authMiddleware],
  16. responses: {
  17. 200: {
  18. description: '登出成功',
  19. content: {
  20. 'application/json': {
  21. schema: SuccessSchema
  22. }
  23. }
  24. },
  25. 401: {
  26. description: '未授权',
  27. content: {
  28. 'application/json': {
  29. schema: ErrorSchema
  30. }
  31. }
  32. },
  33. 500: {
  34. description: '服务器错误',
  35. content: {
  36. 'application/json': {
  37. schema: ErrorSchema
  38. }
  39. }
  40. }
  41. }
  42. });
  43. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  44. try {
  45. // 在路由处理函数内部初始化服务
  46. const userService = new UserService(AppDataSource);
  47. const authService = new AuthService(userService);
  48. const token = c.get('token');
  49. const decoded = authService.verifyToken(token);
  50. if (!decoded) {
  51. return c.json({ code: 401, message: '未授权' }, 401);
  52. }
  53. await authService.logout(token);
  54. return c.json({ message: '登出成功' }, 200);
  55. } catch (error) {
  56. console.error('登出失败:', error);
  57. return c.json({ code: 500, message: '登出失败' }, 500);
  58. }
  59. });
  60. export default app;