create.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
  2. import { AuthService } from '../../../modules/auth/auth.service'
  3. import { UserService } from '../../../modules/users/user.service'
  4. import { z } from '@hono/zod-openapi'
  5. import { AppDataSource } from '../../../data-source'
  6. import { ErrorSchema } from '../../../utils/errorHandler'
  7. import { AuthContext } from '../../../types/context'
  8. import { UserSchema } from '@/server/modules/users/user.schema'
  9. import { parseWithAwait } from '@/server/utils/parseWithAwait'
  10. const RegisterSchema = z.object({
  11. username: z.string().min(3).openapi({
  12. example: 'john_doe',
  13. description: '用户名'
  14. }),
  15. password: z.string().min(6).openapi({
  16. example: 'password123',
  17. description: '密码'
  18. }),
  19. email: z.string().email().openapi({
  20. example: 'john@example.com',
  21. description: '邮箱'
  22. }).optional()
  23. })
  24. const TokenResponseSchema = z.object({
  25. token: z.string().openapi({
  26. example: 'jwt.token.here',
  27. description: 'JWT Token'
  28. }),
  29. user: UserSchema.omit({ password: true })
  30. })
  31. const userService = new UserService(AppDataSource)
  32. const authService = new AuthService(userService)
  33. const registerRoute = createRoute({
  34. method: 'post',
  35. path: '/register',
  36. request: {
  37. body: {
  38. content: {
  39. 'application/json': {
  40. schema: RegisterSchema
  41. }
  42. }
  43. }
  44. },
  45. responses: {
  46. 201: {
  47. description: '注册成功',
  48. content: {
  49. 'application/json': {
  50. schema: TokenResponseSchema
  51. }
  52. }
  53. },
  54. 400: {
  55. description: '用户名已存在',
  56. content: {
  57. 'application/json': {
  58. schema: ErrorSchema
  59. }
  60. }
  61. }
  62. }
  63. })
  64. const app = new OpenAPIHono<AuthContext>().openapi(registerRoute, async (c) => {
  65. const { username, password, email } = c.req.valid('json')
  66. const user = await userService.createUser({ username, password, email })
  67. const token = authService.generateToken(user)
  68. return c.json({
  69. token,
  70. user: await parseWithAwait(UserSchema, user)
  71. }, 201)
  72. })
  73. export default app