wechat-bind.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi';
  3. import { WechatAuthService } from '@/server/modules/wechat/wechat-auth.service';
  4. import { ErrorSchema } from '@/server/utils/errorHandler';
  5. import { AppDataSource } from '@/server/data-source';
  6. import { UserService } from '@/server/modules/users/user.service';
  7. import { AuthService } from '@/server/modules/auth/auth.service';
  8. import { UserSchema } from '@/server/modules/users/user.schema';
  9. import { authMiddleware } from '@/server/middleware/auth.middleware';
  10. import { AuthContext } from '@/server/types/context';
  11. import { parseWithAwait } from '@/server/utils/parseWithAwait';
  12. const BindWechatSchema = z.object({
  13. code: z.string().min(1).openapi({
  14. example: '0816TxlL1Qe3QY0qgDlL1pQxlL16TxlO',
  15. description: '微信授权code'
  16. })
  17. });
  18. const userService = new UserService(AppDataSource);
  19. const authService = new AuthService(userService);
  20. const wechatAuthService = new WechatAuthService(userService, authService);
  21. const bindWechatRoute = createRoute({
  22. method: 'post',
  23. path: '/bind',
  24. middleware: [authMiddleware],
  25. request: {
  26. body: {
  27. content: {
  28. 'application/json': {
  29. schema: BindWechatSchema
  30. }
  31. }
  32. }
  33. },
  34. responses: {
  35. 200: {
  36. description: '绑定微信账号成功',
  37. content: {
  38. 'application/json': {
  39. schema: UserSchema
  40. }
  41. }
  42. },
  43. 400: {
  44. description: '请求参数错误',
  45. content: {
  46. 'application/json': {
  47. schema: ErrorSchema
  48. }
  49. }
  50. },
  51. 401: {
  52. description: '认证失败',
  53. content: {
  54. 'application/json': {
  55. schema: ErrorSchema
  56. }
  57. }
  58. }
  59. }
  60. });
  61. const app = new OpenAPIHono<AuthContext>().openapi(bindWechatRoute, async (c) => {
  62. try {
  63. const user = c.get('user');
  64. const { code } = await c.req.json();
  65. const result = await wechatAuthService.bindWechatToUser(user.id, code);
  66. // 使用 parseWithAwait 确保返回数据符合Schema定义
  67. const validatedResult = await parseWithAwait(UserSchema, result);
  68. return c.json(validatedResult, 200);
  69. } catch (error) {
  70. return c.json({
  71. code: 400,
  72. message: error instanceof Error ? error.message : '绑定微信账号失败'
  73. }, 400);
  74. }
  75. });
  76. export default app;