create.ts 1.8 KB

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