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

export class TraceUtil {
  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 (t) => [t.get(), `[${f.name}]`];
  }

  static withClassTrace<C extends object, T, Trace>(
    c: C,
  ): ITraceableMapper<
    T,
    ITraceableTuple<T, Trace | Array<Trace>>,
    Trace
  > {
    return (t) => [t.get(), `[${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();
  }
}