register.route.mt.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { AuthService } from '../services/index.mt';
  3. import { UserServiceMt } from '@d8d/core-module-mt/user-module-mt';
  4. import { z } from '@hono/zod-openapi';
  5. import { AppDataSource } from '@d8d/shared-utils';
  6. import { ErrorSchema } from '@d8d/shared-utils';
  7. import { AuthContext } from '@d8d/shared-types';
  8. import { UserSchemaMt } from '@d8d/core-module-mt/user-module-mt';
  9. import { parseWithAwait } from '@d8d/shared-utils';
  10. import { TokenResponseSchema } from '../schemas/index.mt';
  11. const RegisterSchema = z.object({
  12. username: z.string().min(3).openapi({
  13. example: 'john_doe',
  14. description: '用户名'
  15. }),
  16. password: z.string().min(6).openapi({
  17. example: 'password123',
  18. description: '密码'
  19. }),
  20. email: z.string().email().openapi({
  21. example: 'john@example.com',
  22. description: '邮箱'
  23. }).optional()
  24. });
  25. const registerRoute = createRoute({
  26. method: 'post',
  27. path: '/register',
  28. request: {
  29. body: {
  30. content: {
  31. 'application/json': {
  32. schema: RegisterSchema
  33. }
  34. }
  35. }
  36. },
  37. responses: {
  38. 201: {
  39. description: '注册成功',
  40. content: {
  41. 'application/json': {
  42. schema: TokenResponseSchema
  43. }
  44. }
  45. },
  46. 400: {
  47. description: '用户名已存在',
  48. content: {
  49. 'application/json': {
  50. schema: ErrorSchema
  51. }
  52. }
  53. }
  54. }
  55. });
  56. const app = new OpenAPIHono<AuthContext>().openapi(registerRoute, async (c) => {
  57. // 在路由处理函数内部初始化服务
  58. const userService = new UserServiceMt(AppDataSource);
  59. const authService = new AuthService(userService);
  60. const { username, password, email } = c.req.valid('json');
  61. // 从请求头或查询参数中提取租户ID
  62. const tenantId = c.req.header('X-Tenant-Id') || c.req.query('tenantId');
  63. const tenantIdNumber = tenantId ? parseInt(tenantId, 10) : undefined;
  64. const userData: any = { username, password, email };
  65. // 如果提供了租户ID,则设置租户ID
  66. if (tenantIdNumber) {
  67. userData.tenantId = tenantIdNumber;
  68. }
  69. const user = await userService.createUser(userData, tenantIdNumber);
  70. const token = authService.generateToken(user);
  71. return c.json({
  72. token,
  73. user: await parseWithAwait(UserSchemaMt, user)
  74. }, 201);
  75. });
  76. export default app;