post.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '../../modules/users/user.service';
  3. import { authMiddleware } from '../../middleware/auth.middleware';
  4. import { ErrorSchema } from '../../utils/errorHandler';
  5. import { AppDataSource } from '../../data-source';
  6. import { AuthContext } from '../../types/context';
  7. import { UserSchema, CreateUserDto } from '@/server/modules/users/user.schema';
  8. const userService = new UserService(AppDataSource);
  9. const createUserRoute = createRoute({
  10. method: 'post',
  11. path: '/',
  12. middleware: authMiddleware,
  13. request: {
  14. body: {
  15. content: {
  16. 'application/json': {
  17. schema: CreateUserDto
  18. }
  19. }
  20. }
  21. },
  22. responses: {
  23. 201: {
  24. description: '创建成功',
  25. content: {
  26. 'application/json': {
  27. schema: UserSchema
  28. }
  29. }
  30. },
  31. 400: {
  32. description: '输入数据无效',
  33. content: {
  34. 'application/json': {
  35. schema: ErrorSchema
  36. }
  37. }
  38. },
  39. 500: {
  40. description: '服务器错误',
  41. content: {
  42. 'application/json': {
  43. schema: ErrorSchema
  44. }
  45. }
  46. }
  47. }
  48. });
  49. const app = new OpenAPIHono<AuthContext>().openapi(createUserRoute, async (c) => {
  50. try {
  51. const data = c.req.valid('json');
  52. const user = await userService.createUser(data);
  53. return c.json(user, 201);
  54. } catch (error) {
  55. return c.json({ code: 500, message: '服务器错误' }, 500);
  56. }
  57. });
  58. export default app;