48 lines
1.9 KiB
TypeScript
48 lines
1.9 KiB
TypeScript
import { type Cause, Context, Effect, Layer, Option, Pipeable, Predicate, PubSub, type Scope } from "effect"
|
|
|
|
|
|
export const ErrorObserverTypeId: unique symbol = Symbol.for("@effect-fc/ErrorObserver/ErrorObserver")
|
|
export type ErrorObserverTypeId = typeof ErrorObserverTypeId
|
|
|
|
export interface ErrorObserver<in out E = never> extends Pipeable.Pipeable {
|
|
readonly [ErrorObserverTypeId]: ErrorObserverTypeId
|
|
handle<A, E1, R>(effect: Effect.Effect<A, E1, R>): Effect.Effect<A, E1, R>
|
|
readonly subscribe: Effect.Effect<PubSub.Subscription<Cause.Cause<E>>, never, Scope.Scope>
|
|
}
|
|
|
|
export const ErrorObserver = <E = never>() => Context.Service<ErrorObserver<E>>(
|
|
"@effect-fc/ErrorObserver/ErrorObserver",
|
|
)
|
|
|
|
export class ErrorObserverImpl<in out E = never> extends Pipeable.Class implements ErrorObserver<E> {
|
|
readonly [ErrorObserverTypeId]: ErrorObserverTypeId = ErrorObserverTypeId
|
|
|
|
constructor(readonly pubsub: PubSub.PubSub<Cause.Cause<E>>) {
|
|
super()
|
|
}
|
|
|
|
get subscribe(): Effect.Effect<PubSub.Subscription<Cause.Cause<E>>, never, Scope.Scope> {
|
|
return PubSub.subscribe(this.pubsub)
|
|
}
|
|
|
|
handle<A, E1, R>(effect: Effect.Effect<A, E1, R>): Effect.Effect<A, E1, R> {
|
|
return Effect.tapCause(effect, cause => Effect.asVoid(
|
|
PubSub.publish(this.pubsub, cause as unknown as Cause.Cause<E>),
|
|
))
|
|
}
|
|
}
|
|
|
|
export const isErrorObserver = (u: unknown): u is ErrorObserver<unknown> => Predicate.hasProperty(u, ErrorObserverTypeId)
|
|
|
|
export const layer: Layer.Layer<ErrorObserver> = Layer.effect(ErrorObserver())(
|
|
Effect.map(PubSub.unbounded<Cause.Cause<never>>(), pubsub => new ErrorObserverImpl(pubsub)),
|
|
)
|
|
|
|
export const handle = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => Effect.flatMap(
|
|
Effect.serviceOption(ErrorObserver()),
|
|
Option.match({
|
|
onSome: observer => observer.handle(effect),
|
|
onNone: () => effect,
|
|
}),
|
|
)
|