| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
- import { AuthService } from '../../../modules/auth/auth.service'
- import { UserService } from '../../../modules/users/user.service'
- import { z } from '@hono/zod-openapi'
- import { ErrorSchema } from '../../../utils/errorHandler'
- import { AppDataSource } from '../../../data-source'
- import { AuthContext } from '../../../types/context'
- import { UserSchema } from '@/server/modules/users/user.schema'
- import { parseWithAwait } from '@/server/utils/parseWithAwait'
- const userService = new UserService(AppDataSource)
- const authService = new AuthService(userService)
- const LoginSchema = z.object({
- username: z.string().min(3).openapi({
- example: 'admin',
- description: '用户名'
- }),
- password: z.string().min(6).openapi({
- example: 'admin123',
- description: '密码'
- })
- })
- const UserResponseSchema = UserSchema.omit({ password: true })
- const TokenResponseSchema = z.object({
- token: z.string().openapi({
- example: 'jwt.token.here',
- description: 'JWT Token'
- }),
- user: UserResponseSchema
- })
- const loginRoute = createRoute({
- method: 'post',
- path: '/login',
- request: {
- body: {
- content: {
- 'application/json': {
- schema: LoginSchema
- }
- }
- }
- },
- responses: {
- 200: {
- description: '登录成功',
- content: {
- 'application/json': {
- schema: TokenResponseSchema
- }
- }
- },
- 401: {
- description: '用户名或密码错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- })
- const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
- try {
- const { username, password } = c.req.valid('json')
- const result = await authService.login(username, password)
- return c.json(await parseWithAwait(TokenResponseSchema, result), 200)
- } catch (error) {
- console.error('登录失败:', error)
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '登录失败'
- }, 500)
- }
- });
- export default app
|