summaryrefslogtreecommitdiff
path: root/u/trace/trace.ts
blob: 5d5c59b17998bea0b4628c1736400519ea0186a2 (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
import type { Callable } from "@emprespresso/utils";
import {
  type ITraceableMapper,
  type ITraceableTuple,
  TraceableImpl,
  TraceableLogger,
} from "./mod.ts";

export class Traceable<T> extends TraceableImpl<T, TraceableLogger> {
  static from<T>(t: T) {
    return new Traceable(t, new TraceableLogger());
  }

  static withFunctionTrace<F extends Callable, T>(
    f: F,
  ): ITraceableMapper<T, TraceableLogger, ITraceableTuple<T>> {
    return (t) => [t.item, f.name];
  }

  static withClassTrace<C extends object, T>(
    c: C,
  ): ITraceableMapper<T, TraceableLogger, ITraceableTuple<T>> {
    return (t) => [t.item, c.constructor.name];
  }

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