diff options
author | Elizabeth Hunt <me@liz.coffee> | 2025-07-27 17:03:10 -0700 |
---|---|---|
committer | Elizabeth Hunt <me@liz.coffee> | 2025-07-27 18:30:30 -0700 |
commit | 9970036d203ba2d0a46b35ba6fad21d49441cdd4 (patch) | |
tree | a585d13933bf4149dcb07e28526063d071453105 /lib/trace/util.ts | |
download | pengueno-9970036d203ba2d0a46b35ba6fad21d49441cdd4.tar.gz pengueno-9970036d203ba2d0a46b35ba6fad21d49441cdd4.zip |
hai
Diffstat (limited to 'lib/trace/util.ts')
-rw-r--r-- | lib/trace/util.ts | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/lib/trace/util.ts b/lib/trace/util.ts new file mode 100644 index 0000000..ec67571 --- /dev/null +++ b/lib/trace/util.ts @@ -0,0 +1,59 @@ +import { + IEither, + IMetric, + isEither, + ITraceable, + ITraceWith, + LogLevel, + ResultMetric, + type Callable, + type ITraceableMapper, +} from '@emprespresso/pengueno'; + +export class TraceUtil { + 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(); + } + + static traceResultingEither<TErr, TOk, Trace>( + metric?: ResultMetric, + warnOnFailure = false, + ): ITraceableMapper<IEither<TErr, TOk>, ITraceable<IEither<TErr, TOk>, Trace>, Trace> { + return (t) => { + if (metric) + t.trace.trace( + t.get().fold( + (_err) => <Trace>(warnOnFailure ? metric.warn : metric.failure), + (_ok) => <Trace>metric.success, + ), + ); + return t.traceScope((_t) => + _t.get().fold( + (_err) => <Trace>(warnOnFailure ? LogLevel.WARN : LogLevel.ERROR), + (_ok) => <Trace>LogLevel.INFO, + ), + ); + }; + } + + static withTrace<T, Trace, _Trace extends ITraceWith<Trace>>( + trace: _Trace, + ): ITraceableMapper<T, ITraceable<T, Trace>, Trace> { + return (t) => t.traceScope(() => <Trace>trace); + } + + static withMetricTrace<T, Trace>(metric: IMetric): ITraceableMapper<T, ITraceable<T, Trace>, Trace> { + return TraceUtil.withTrace(<Trace>metric); + } + + static withFunctionTrace<F extends Callable, T, Trace>(f: F): ITraceableMapper<T, ITraceable<T, Trace>, Trace> { + return TraceUtil.withTrace(<Trace>`fn.${f.name}`); + } + + static withClassTrace<C extends object, T, Trace>(c: C): ITraceableMapper<T, ITraceable<T, Trace>, Trace> { + return TraceUtil.withTrace(<Trace>`class.${c.constructor.name}`); + } +} |