register.route.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { AuthService } from '../services';
  3. import { UserService } from '@d8d/user-module';
  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 { UserSchema } from '@d8d/user-module';
  9. import { parseWithAwait } from '@d8d/shared-utils';
  10. import { RegisterSchema, TokenResponseSchema } from '../schemas';
  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 UserService(AppDataSource);
  59. const authService = new AuthService(userService);
  60. const { username, password, email } = c.req.valid('json');
  61. const user = await userService.createUser({ username, password, email });
  62. const token = authService.generateToken(user);
  63. return c.json({
  64. token,
  65. user: await parseWithAwait(UserSchema, user)
  66. }, 201);
  67. });
  68. export default app;