| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { UserService } from '../../modules/users/user.service';
- import { z } from 'zod';
- import { authMiddleware } from '../../middleware/auth.middleware';
- import { ErrorSchema } from '../../utils/errorHandler';
- import { AppDataSource } from '../../data-source';
- import { AuthContext } from '../../types/context';
- import { UserSchema } from '@/server/modules/users/user.entity';
- const userService = new UserService(AppDataSource);
- const CreateUserSchema = UserSchema.omit({
- id: true,
- createdAt: true,
- updatedAt: true,
- })
- const createUserRoute = createRoute({
- method: 'post',
- path: '/',
- middleware: authMiddleware,
- request: {
- body: {
- content: {
- 'application/json': {
- schema: CreateUserSchema
- }
- }
- }
- },
- responses: {
- 201: {
- description: '创建成功',
- content: {
- 'application/json': {
- schema: UserSchema
- }
- }
- },
- 400: {
- description: '输入数据无效',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(createUserRoute, async (c) => {
- try {
- const data = c.req.valid('json');
- const user = await userService.createUser(data);
- return c.json(user, 201);
- } catch (error) {
- return c.json({ code: 500, message: '服务器错误' }, 500);
- }
- });
- export default app;
|