| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { AppDataSource } from '@/server/data-source';
- import { OpportunityService } from '@/server/modules/opportunities/opportunity.service';
- import { OpportunitySchema } from '@/server/modules/opportunities/opportunity.entity';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { logger } from '@/server/utils/logger';
- import { authMiddleware } from '@/server/middleware/auth';
- import { AuthContext } from '@/server/types/context';
- // 创建请求Schema(排除自动生成的字段)
- const CreateOpportunitySchema = OpportunitySchema.omit({
- id: true,
- isDeleted: true,
- createdAt: true,
- updatedAt: true,
- closedAt: true
- });
- // 创建响应Schema
- const CreateOpportunityResponse = z.object({
- code: z.number().openapi({ example: 201 }),
- message: z.string().openapi({ example: '销售机会创建成功' }),
- data: OpportunitySchema
- });
- // 定义路由
- const routeDef = createRoute({
- method: 'post',
- path: '/',
- middleware: [authMiddleware],
- request: {
- body: {
- content: {
- 'application/json': {
- schema: CreateOpportunitySchema
- }
- }
- }
- },
- responses: {
- 201: {
- description: '销售机会创建成功',
- content: {
- 'application/json': {
- schema: CreateOpportunityResponse
- }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 401: {
- description: '未授权访问',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器内部错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- // 创建路由实例
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const body = c.req.valid('json');
- logger.api('Creating opportunity with data: %o', body);
- // 初始化服务
- const opportunityService = new OpportunityService(AppDataSource);
-
- // 创建销售机会
- const newOpportunity = await opportunityService.create({
- ...body,
- // 设置默认值
- isDeleted: 0
- });
-
- return c.json({
- code: 201,
- message: '销售机会创建成功',
- data: newOpportunity
- }, 201);
- } catch (error) {
- logger.error('Error creating opportunity: %o', error);
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '销售机会创建失败'
- }, 500);
- }
- });
- export default app;
|