| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- 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 { AppDataSource } from '../../../data-source'
- import { ErrorSchema } from '../../../utils/errorHandler'
- import { AuthContext } from '../../../types/context'
- import { UserSchema } from '@/server/modules/users/user.schema'
- import { parseWithAwait } from '@/server/utils/parseWithAwait'
- const RegisterSchema = z.object({
- username: z.string().min(3).openapi({
- example: 'john_doe',
- description: '用户名'
- }),
- password: z.string().min(6).openapi({
- example: 'password123',
- description: '密码'
- }),
- email: z.string().email().openapi({
- example: 'john@example.com',
- description: '邮箱'
- }).optional()
- })
- const TokenResponseSchema = z.object({
- token: z.string().openapi({
- example: 'jwt.token.here',
- description: 'JWT Token'
- }),
- user: UserSchema.omit({ password: true })
- })
- const userService = new UserService(AppDataSource)
- const authService = new AuthService(userService)
- const registerRoute = createRoute({
- method: 'post',
- path: '/register',
- request: {
- body: {
- content: {
- 'application/json': {
- schema: RegisterSchema
- }
- }
- }
- },
- responses: {
- 201: {
- description: '注册成功',
- content: {
- 'application/json': {
- schema: TokenResponseSchema
- }
- }
- },
- 400: {
- description: '用户名已存在',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- })
- const app = new OpenAPIHono<AuthContext>().openapi(registerRoute, async (c) => {
- const { username, password, email } = c.req.valid('json')
- const user = await userService.createUser({ username, password, email })
- const token = authService.generateToken(user)
- return c.json({
- token,
- user: await parseWithAwait(UserSchema, user)
- }, 201)
- })
- export default app
|