post.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi';
  3. import { AppDataSource } from '@/server/data-source';
  4. import { OpportunityService } from '@/server/modules/opportunities/opportunity.service';
  5. import { OpportunitySchema } from '@/server/modules/opportunities/opportunity.entity';
  6. import { ErrorSchema } from '@/server/utils/errorHandler';
  7. import { logger } from '@/server/utils/logger';
  8. import { authMiddleware } from '@/server/middleware/auth';
  9. import { AuthContext } from '@/server/types/context';
  10. // 创建请求Schema(排除自动生成的字段)
  11. const CreateOpportunitySchema = OpportunitySchema.omit({
  12. id: true,
  13. isDeleted: true,
  14. createdAt: true,
  15. updatedAt: true,
  16. closedAt: true
  17. });
  18. // 创建响应Schema
  19. const CreateOpportunityResponse = z.object({
  20. code: z.number().openapi({ example: 201 }),
  21. message: z.string().openapi({ example: '销售机会创建成功' }),
  22. data: OpportunitySchema
  23. });
  24. // 定义路由
  25. const routeDef = createRoute({
  26. method: 'post',
  27. path: '/',
  28. middleware: [authMiddleware],
  29. request: {
  30. body: {
  31. content: {
  32. 'application/json': {
  33. schema: CreateOpportunitySchema
  34. }
  35. }
  36. }
  37. },
  38. responses: {
  39. 201: {
  40. description: '销售机会创建成功',
  41. content: {
  42. 'application/json': {
  43. schema: CreateOpportunityResponse
  44. }
  45. }
  46. },
  47. 400: {
  48. description: '请求参数错误',
  49. content: {
  50. 'application/json': {
  51. schema: ErrorSchema
  52. }
  53. }
  54. },
  55. 401: {
  56. description: '未授权访问',
  57. content: {
  58. 'application/json': {
  59. schema: ErrorSchema
  60. }
  61. }
  62. },
  63. 500: {
  64. description: '服务器内部错误',
  65. content: {
  66. 'application/json': {
  67. schema: ErrorSchema
  68. }
  69. }
  70. }
  71. }
  72. });
  73. // 创建路由实例
  74. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  75. try {
  76. const body = c.req.valid('json');
  77. logger.api('Creating opportunity with data: %o', body);
  78. // 初始化服务
  79. const opportunityService = new OpportunityService(AppDataSource);
  80. // 创建销售机会
  81. const newOpportunity = await opportunityService.create({
  82. ...body,
  83. // 设置默认值
  84. isDeleted: 0
  85. });
  86. return c.json({
  87. code: 201,
  88. message: '销售机会创建成功',
  89. data: newOpportunity
  90. }, 201);
  91. } catch (error) {
  92. logger.error('Error creating opportunity: %o', error);
  93. return c.json({
  94. code: 500,
  95. message: error instanceof Error ? error.message : '销售机会创建失败'
  96. }, 500);
  97. }
  98. });
  99. export default app;