@@ -13,25 +13,65 @@ import { createContextFromRequest } from '../../../shared/types/context.js';
1313/**
1414 * CreateTask Handler
1515 * HTTP 适配层:处理创建任务的 HTTP 请求
16+ * 负责日志记录和性能监控,使用 Fastify 的 request.log(自动包含请求上下文)
1617 * 错误由全局错误处理中间件统一处理
1718 */
1819export async function createTaskHandler (
1920 deps : HandlerDependencies ,
2021 req : FastifyRequest < { Body : CreateTaskRequest } > ,
2122 reply : FastifyReply
2223) : Promise < void > {
23- // 1. 获取用户 ID(从 JWT Token 中提取)
24+ const startTime = Date . now ( ) ;
2425 const userId = requireUserId ( req ) ;
2526
26- // 2. 转换为 Domain Input
27- const input = toCreateTaskInput ( userId , req . body ) ;
27+ // 使用 Fastify 的 request.log(自动包含 traceId, requestId)
28+ req . log . info ( {
29+ userId,
30+ title : req . body . title ,
31+ priority : req . body . priority ,
32+ hasDueDate : ! ! req . body . due_date ,
33+ tagCount : req . body . tags ?. length || 0 ,
34+ } , 'Creating task' ) ;
2835
29- // 3. 创建请求上下文
30- const ctx = createContextFromRequest ( { userId, ...req } ) ;
36+ try {
37+ // 转换为 Domain Input
38+ const input = toCreateTaskInput ( userId , req . body ) ;
3139
32- // 4. 调用 Domain Service(错误会自动向上抛出,由全局错误处理中间件处理)
33- const output = await deps . taskService . createTask ( ctx , input ) ;
40+ // 创建请求上下文
41+ const ctx = createContextFromRequest ( { userId , ... req } ) ;
3442
35- // 4. 转换为 HTTP 响应
36- reply . code ( 200 ) . send ( toCreateTaskResponse ( output . task ) ) ;
43+ // 调用 Domain Service(纯业务逻辑,不包含日志)
44+ const output = await deps . taskService . createTask ( ctx , input ) ;
45+
46+ // 记录成功日志和性能指标
47+ const duration = Date . now ( ) - startTime ;
48+ req . log . info ( {
49+ taskId : output . task . id ,
50+ userId : output . task . userId ,
51+ duration,
52+ } , 'Task created successfully' ) ;
53+
54+ // 慢操作警告
55+ if ( duration > 1000 ) {
56+ req . log . warn ( {
57+ taskId : output . task . id ,
58+ duration,
59+ threshold : 1000 ,
60+ } , 'Slow task creation' ) ;
61+ }
62+
63+ // 转换为 HTTP 响应
64+ reply . code ( 200 ) . send ( toCreateTaskResponse ( output . task ) ) ;
65+ } catch ( error ) {
66+ // 记录错误日志
67+ const duration = Date . now ( ) - startTime ;
68+ req . log . error ( {
69+ userId,
70+ title : req . body . title ,
71+ duration,
72+ error : error instanceof Error ? error . message : String ( error ) ,
73+ stack : error instanceof Error ? error . stack : undefined ,
74+ } , 'Failed to create task' ) ;
75+ throw error ; // 由全局错误处理器处理
76+ }
3777}
0 commit comments