|
@@ -6,6 +6,7 @@ import { ErrorSchema } from '../../../utils/errorHandler'
|
|
|
import { AppDataSource } from '../../../data-source'
|
|
import { AppDataSource } from '../../../data-source'
|
|
|
import { AuthContext } from '../../../types/context'
|
|
import { AuthContext } from '../../../types/context'
|
|
|
import { UserSchema } from '@/server/modules/users/user.schema'
|
|
import { UserSchema } from '@/server/modules/users/user.schema'
|
|
|
|
|
+import { parseWithAwait } from '@/server/utils/parseWithAwait'
|
|
|
|
|
|
|
|
const userService = new UserService(AppDataSource)
|
|
const userService = new UserService(AppDataSource)
|
|
|
const authService = new AuthService(userService)
|
|
const authService = new AuthService(userService)
|
|
@@ -21,7 +22,7 @@ const LoginSchema = z.object({
|
|
|
})
|
|
})
|
|
|
})
|
|
})
|
|
|
|
|
|
|
|
-const UserResponseSchema = UserSchema
|
|
|
|
|
|
|
+const UserResponseSchema = UserSchema.omit({ password: true })
|
|
|
|
|
|
|
|
const TokenResponseSchema = z.object({
|
|
const TokenResponseSchema = z.object({
|
|
|
token: z.string().openapi({
|
|
token: z.string().openapi({
|
|
@@ -59,13 +60,29 @@ const loginRoute = createRoute({
|
|
|
schema: ErrorSchema
|
|
schema: ErrorSchema
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
+ },
|
|
|
|
|
+ 500: {
|
|
|
|
|
+ description: '服务器错误',
|
|
|
|
|
+ content: {
|
|
|
|
|
+ 'application/json': {
|
|
|
|
|
+ schema: ErrorSchema
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
})
|
|
})
|
|
|
const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
|
|
const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
|
|
|
- const { username, password } = c.req.valid('json')
|
|
|
|
|
- const result = await authService.login(username, password)
|
|
|
|
|
- return c.json(result, 200)
|
|
|
|
|
|
|
+ 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
|
|
export default app
|