mapErrorsToTRPC

This commit is contained in:
Julien Valverdé
2024-07-12 03:53:04 +02:00
parent a9864d6851
commit a0382a2427
2 changed files with 35 additions and 5 deletions

View File

@@ -1,14 +1,21 @@
import type { TRPCError } from "@trpc/server"
import type { Effect, Runtime } from "effect"
import type { Request } from "express"
import type { RuntimeFiber } from "effect/Fiber"
import type { Services } from "../Services"
export interface TRPCContext {
runtime: Runtime.Runtime<Services>
run: <A, E>(
effect: Effect.Effect<A, E, Services>,
options?: { readonly signal?: AbortSignal }
options?: { readonly signal?: AbortSignal },
) => Promise<A>
fork: <A, E>(
effect: Effect.Effect<A, E, Services>,
options?: Runtime.RunForkOptions,
) => RuntimeFiber<A, TRPCError>
// req: Request
}

View File

@@ -19,11 +19,27 @@ export class TRPCContextCreator extends Context.Tag("TRPCContextCreator")<TRPCCo
export module TRPCContextCreator {
export const Live = Layer.effect(TRPCContextCreator, Effect.gen(function*() {
const runtime = yield* Effect.runtime<Services>()
const run = Runtime.runPromise(runtime)
const run = <A, E>(
effect: Effect.Effect<A, E, Services>,
options?: { readonly signal?: AbortSignal },
) => Runtime.runPromise(runtime)(
effect.pipe(mapErrorsToTRPC),
options,
)
const fork = <A, E>(
effect: Effect.Effect<A, E, Services>,
options?: Runtime.RunForkOptions,
) => Runtime.runFork(runtime)(
effect.pipe(mapErrorsToTRPC),
options,
)
return ({ req }) => ({
runtime,
run,
fork,
// req,
})
}))
@@ -36,13 +52,20 @@ const mapErrorsToTRPC = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Die: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
Interrupt: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
Fail: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
Empty: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
Parallel: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
Sequential: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause })
),
})
)