| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from 'zod';
- import { AppDataSource } from '@/server/data-source';
- import { TicketService } from '@/server/modules/tickets/ticket.service';
- import { TicketSchema } from '@/server/modules/tickets/ticket.entity';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { authMiddleware } from '@/server/middleware/auth';
- import { AuthContext } from '@/server/types/context';
- import { logger } from '@/server/utils/logger';
- // 初始化服务
- const ticketService = new TicketService(AppDataSource);
- // 创建工单请求Schema
- const CreateTicketSchema = z.object({
- title: z.string().min(3).max(255).openapi({
- example: '系统登录异常',
- description: '工单标题'
- }),
- description: z.string().min(10).openapi({
- example: '用户报告无法登录系统,提示密码错误,但确认密码正确',
- description: '工单描述'
- }),
- customerId: z.number().int().positive().openapi({
- example: 1,
- description: '客户ID'
- }),
- priority: z.enum(['0', '1', '2', '3']).default('1').openapi({
- example: '2',
- description: '工单优先级(0:低, 1:中, 2:高, 3:紧急)'
- }),
- type: z.string().optional().openapi({
- example: 'login',
- description: '工单类型'
- }),
- relatedAsset: z.string().optional().openapi({
- example: 'server-01',
- description: '相关资产'
- })
- });
- // 响应Schema
- const ResponseSchema = z.object({
- code: z.number().openapi({ example: 200, description: '状态码' }),
- message: z.string().openapi({ example: '工单创建成功', description: '消息' }),
- data: TicketSchema
- });
- // 路由定义
- const routeDef = createRoute({
- method: 'post',
- path: '/',
- middleware: [authMiddleware],
- request: {
- body: {
- content: {
- 'application/json': { schema: CreateTicketSchema }
- }
- }
- },
- responses: {
- 200: {
- description: '成功创建工单',
- content: {
- 'application/json': { schema: ResponseSchema }
- }
- },
- 400: {
- 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');
- const user = c.get('user');
-
- // 创建工单
- const ticket = await ticketService.create({
- title: body.title,
- description: body.description,
- customerId: body.customerId,
- priority: parseInt(body.priority, 10),
- type: body.type,
- createdBy: user.id,
- status: 0 // 0表示新建状态
- });
-
- return c.json({
- code: 200,
- message: '工单创建成功',
- data: ticket
- }, 200);
- } catch (error) {
- logger.error('Error creating ticket:', error);
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '创建工单失败'
- }, 500);
- }
- });
- export default app;
|