* 根据 handler 名称执行任务
(
handler: string,
payload?: T
)
| 51 | * 根据 handler 名称执行任务 |
| 52 | */ |
| 53 | async executeTask<T = any, R = any>( |
| 54 | handler: string, |
| 55 | payload?: T |
| 56 | ): Promise<R> { |
| 57 | const TaskClass = this.taskHandlers.get(handler); |
| 58 | |
| 59 | if (!TaskClass) { |
| 60 | throw new MidwayCommonError( |
| 61 | `Task handler "${handler}" not found. Did you forget to use @PiscinaTask('${handler}') decorator?` |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | const ctx = this.app.createAnonymousContext(); |
| 66 | const traceService = this.applicationContext.get(MidwayTraceService); |
| 67 | const traceMetaResolver = (this.configurationOptions as any)?.tracing?.meta; |
| 68 | const traceEnabled = |
| 69 | (this.configurationOptions as any)?.tracing?.enable !== false; |
| 70 | const traceExtractor = (this.configurationOptions as any)?.tracing |
| 71 | ?.extractor; |
| 72 | const entryCarrier = |
| 73 | typeof traceExtractor === 'function' |
| 74 | ? traceExtractor({ |
| 75 | ctx, |
| 76 | request: payload, |
| 77 | custom: { |
| 78 | handler, |
| 79 | }, |
| 80 | }) |
| 81 | : {}; |
| 82 | return await traceService.runWithEntrySpan( |
| 83 | `piscina ${handler}`, |
| 84 | { |
| 85 | enable: traceEnabled, |
| 86 | carrier: entryCarrier, |
| 87 | attributes: { |
| 88 | 'midway.protocol': 'piscina', |
| 89 | 'midway.piscina.handler': handler, |
| 90 | }, |
| 91 | meta: traceMetaResolver, |
| 92 | metaArgs: { |
| 93 | ctx, |
| 94 | carrier: entryCarrier, |
| 95 | request: payload, |
| 96 | custom: { |
| 97 | handler, |
| 98 | }, |
| 99 | }, |
| 100 | }, |
| 101 | async () => { |
| 102 | const taskInstance = await ctx.requestContext.getAsync<any>(TaskClass); |
| 103 | |
| 104 | if (!taskInstance || typeof taskInstance.execute !== 'function') { |
| 105 | throw new MidwayCommonError( |
| 106 | `Task "${handler}" must implement execute method` |
| 107 | ); |
| 108 | } |
| 109 | |
| 110 | return await taskInstance.execute(payload); |
no test coverage detected