2
0

mini-login.route.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi';
  3. import { MiniAuthService } from '../services';
  4. import { AppDataSource } from '@d8d/shared-utils';
  5. import { ErrorSchema } from '@d8d/shared-utils';
  6. import { UserEntity } from '@d8d/user-module';
  7. import { MiniLoginSchema, MiniLoginResponseSchema } from '../schemas';
  8. const miniLoginRoute = createRoute({
  9. method: 'post',
  10. path: '/mini-login',
  11. request: {
  12. body: {
  13. content: {
  14. 'application/json': {
  15. schema: MiniLoginSchema
  16. }
  17. }
  18. }
  19. },
  20. responses: {
  21. 200: {
  22. description: '小程序登录成功',
  23. content: {
  24. 'application/json': {
  25. schema: MiniLoginResponseSchema
  26. }
  27. }
  28. },
  29. 400: {
  30. description: '参数错误',
  31. content: {
  32. 'application/json': {
  33. schema: ErrorSchema
  34. }
  35. }
  36. },
  37. 500: {
  38. description: '服务器错误',
  39. content: {
  40. 'application/json': {
  41. schema: ErrorSchema
  42. }
  43. }
  44. }
  45. }
  46. });
  47. const app = new OpenAPIHono().openapi(miniLoginRoute, async (c) => {
  48. try {
  49. // 在路由处理函数内部初始化服务
  50. const miniAuthService = new MiniAuthService(AppDataSource);
  51. const { code, userInfo } = c.req.valid('json');
  52. const result = await miniAuthService.miniLogin(code);
  53. // 如果有用户信息,更新用户资料
  54. if (userInfo) {
  55. await miniAuthService.updateUserProfile(result.user.id, {
  56. nickname: userInfo.nickName,
  57. avatarUrl: userInfo.avatarUrl
  58. });
  59. // 重新获取更新后的用户信息
  60. const updatedUser = await AppDataSource.getRepository(UserEntity).findOne({
  61. where: { id: result.user.id },
  62. relations: ['avatarFile']
  63. });
  64. if (updatedUser) {
  65. result.user = updatedUser;
  66. }
  67. }
  68. return c.json({
  69. token: result.token,
  70. user: {
  71. id: result.user.id,
  72. username: result.user.username,
  73. nickname: result.user.nickname,
  74. phone: result.user.phone,
  75. email: result.user.email,
  76. avatarFileId: result.user.avatarFileId,
  77. registrationSource: result.user.registrationSource
  78. },
  79. isNewUser: result.isNewUser
  80. }, 200);
  81. } catch (error) {
  82. const { code = 500, message = '登录失败' } = error as Error & { code?: number };
  83. return c.json({ code, message }, 500);
  84. }
  85. });
  86. export default app;