-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrace.decorator.ts
More file actions
60 lines (59 loc) · 2.46 KB
/
trace.decorator.ts
File metadata and controls
60 lines (59 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { executionTrace, TraceContext } from './trace';
import { extractClassMethodMetadata } from '../common/utils/functionMetadata';
import { isAsync } from '../common/utils/isAsync';
/**
* Method decorator to trace function execution, capturing metadata, inputs, outputs, and errors.
*
* @param onTraceEvent - handle function of the trace context.
* @param additionalContext - Additional metadata to attach to the trace context.
* @param options - Configuration options:
* - `contextKey`: Key to store trace context on the instance.
* - `errorStrategy`: Determines whether errors should be caught (`'catch'`) or thrown (`'throw'`).
*
* @returns A method decorator that wraps the original function with execution tracing.
*/
export function trace<O>(
onTraceEvent: (traceContext: TraceContext<O>) => void,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
additionalContext: Record<string, any> = {},
options: { contextKey?: string; errorStrategy?: 'catch' | 'throw' } = {
contextKey: undefined,
errorStrategy: 'throw'
}
): MethodDecorator {
return function (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor): void {
const originalMethod = descriptor.value;
descriptor.value = function (...args: unknown[]) {
const thisTraceContext = {
metadata: extractClassMethodMetadata(target.constructor.name, propertyKey, originalMethod),
...additionalContext
};
if (options.contextKey) {
this[options.contextKey] = thisTraceContext;
}
if (isAsync(originalMethod)) {
return (executionTrace.bind(this) as typeof executionTrace<O>)(
originalMethod.bind(this),
args,
(traceContext) => {
return (onTraceEvent.bind(this) as typeof onTraceEvent)({ ...traceContext, ...thisTraceContext });
},
options
)?.then((r) => (options?.errorStrategy === 'catch' ? r.errors : r.outputs));
} else {
const result = (executionTrace.bind(this) as typeof executionTrace<O>)(
originalMethod.bind(this) as () => O,
args,
(traceContext) => {
return (onTraceEvent.bind(this) as typeof onTraceEvent)({ ...traceContext, ...thisTraceContext });
},
options
);
if (result instanceof Promise) {
return result.then((r) => (options?.errorStrategy === 'catch' ? r.errors : r.outputs));
}
return result?.outputs;
}
};
};
}