summaryrefslogtreecommitdiff
path: root/u/trace/util.ts
blob: 302c8e4766b4c9bb41afb037b00eb56b5a4dc624 (plain)
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
import type {
  Callable,
  IMetric,
  ITraceableMapper,
  ITraceableTuple,
  MetricsTraceSupplier,
} from "@emprespresso/pengueno";

export class TraceUtil {
  static withTrace<T, Trace>(
    trace: string,
  ): ITraceableMapper<
    T,
    ITraceableTuple<T, Trace | Array<Trace>>,
    Trace
  > {
    return (t) => [t.get(), `[${trace}]`];
  }

  static withMetricTrace<T, Trace extends MetricsTraceSupplier>(
    metric: IMetric,
  ): ITraceableMapper<
    T,
    ITraceableTuple<T, Trace | Array<Trace>>,
    Trace
  > {
    return (t) => [t.get(), metric as Trace];
  }

  static withFunctionTrace<F extends Callable, T, Trace>(
    f: F,
  ): ITraceableMapper<
    T,
    ITraceableTuple<T, Trace | Array<Trace>>,
    Trace
  > {
    return TraceUtil.withTrace(f.name);
  }

  static withClassTrace<C extends object, T, Trace>(
    c: C,
  ): ITraceableMapper<
    T,
    ITraceableTuple<T, Trace | Array<Trace>>,
    Trace
  > {
    return TraceUtil.withTrace(c.constructor.name);
  }

  static promiseify<T, U, Trace>(
    mapper: ITraceableMapper<T, U, Trace>,
  ): ITraceableMapper<Promise<T>, Promise<U>, Trace> {
    return (traceablePromise) =>
      traceablePromise.flatMapAsync(async (t) =>
        t.move(await t.get()).map(mapper)
      ).get();
  }
}