post.ts 1.8 KB

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