post.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 { ErrorSchema } from '../../../utils/errorHandler'
  6. import { AppDataSource } from '../../../data-source'
  7. import { AuthContext } from '../../../types/context'
  8. import { UserSchema } from '@/server/modules/users/user.schema'
  9. import { parseWithAwait } from '@/server/utils/parseWithAwait'
  10. const userService = new UserService(AppDataSource)
  11. const authService = new AuthService(userService)
  12. const LoginSchema = z.object({
  13. username: z.string().min(3).openapi({
  14. example: 'admin',
  15. description: '用户名'
  16. }),
  17. password: z.string().min(6).openapi({
  18. example: 'admin123',
  19. description: '密码'
  20. })
  21. })
  22. const UserResponseSchema = UserSchema.omit({ password: true })
  23. const TokenResponseSchema = z.object({
  24. token: z.string().openapi({
  25. example: 'jwt.token.here',
  26. description: 'JWT Token'
  27. }),
  28. user: UserResponseSchema
  29. })
  30. const loginRoute = createRoute({
  31. method: 'post',
  32. path: '/login',
  33. request: {
  34. body: {
  35. content: {
  36. 'application/json': {
  37. schema: LoginSchema
  38. }
  39. }
  40. }
  41. },
  42. responses: {
  43. 200: {
  44. description: '登录成功',
  45. content: {
  46. 'application/json': {
  47. schema: TokenResponseSchema
  48. }
  49. }
  50. },
  51. 401: {
  52. description: '用户名或密码错误',
  53. content: {
  54. 'application/json': {
  55. schema: ErrorSchema
  56. }
  57. }
  58. },
  59. 500: {
  60. description: '服务器错误',
  61. content: {
  62. 'application/json': {
  63. schema: ErrorSchema
  64. }
  65. }
  66. }
  67. }
  68. })
  69. const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
  70. try {
  71. const { username, password } = c.req.valid('json')
  72. const result = await authService.login(username, password)
  73. return c.json(await parseWithAwait(TokenResponseSchema, result), 200)
  74. } catch (error) {
  75. console.error('登录失败:', error)
  76. return c.json({
  77. code: 500,
  78. message: error instanceof Error ? error.message : '登录失败'
  79. }, 500)
  80. }
  81. });
  82. export default app