/
trace.ts
33 lines (30 loc) · 1.09 KB
/
trace.ts
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
import * as express from "express";
import { TraceContext, extractTraceContext, traceContext } from "../common/trace";
import { CloudEvent } from "./core";
type HttpsFunction = (req: express.Request, res: express.Response) => void | Promise<void>;
type CloudEventFunction<T> = (raw: CloudEvent<T>) => any | Promise<any>;
/**
* Wraps v2 handler with trace context.
* @param handler
*
* @internal
*/
export function wrapTraceContext(handler: HttpsFunction): HttpsFunction;
export function wrapTraceContext<T>(handler: CloudEventFunction<T>): CloudEventFunction<T>;
export function wrapTraceContext(
handler: HttpsFunction | CloudEventFunction<unknown>
): HttpsFunction | CloudEventFunction<unknown> {
return (...args) => {
let traceParent: TraceContext | undefined;
if (args.length === 1) {
traceParent = extractTraceContext(args[0]);
} else {
traceParent = extractTraceContext(args[0].headers);
}
if (!traceParent) {
// eslint-disable-next-line prefer-spread
return handler.apply(null, args);
}
return traceContext.run(traceParent, handler, ...args);
};
}