tRPC context work

This commit is contained in:
Julien Valverdé
2024-07-15 02:06:17 +02:00
parent 5a3400f6dd
commit 63f636f231

View File

@@ -1,7 +1,7 @@
import { TRPCError } from "@trpc/server" import { TRPCError } from "@trpc/server"
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express" import type { CreateExpressContextOptions } from "@trpc/server/adapters/express"
import type { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws" import type { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws"
import { Context, Effect, Layer, Runtime } from "effect" import { Cause, Context, Effect, Layer, Runtime } from "effect"
import type { Services } from "../Services" import type { Services } from "../Services"
import { TRPCContextTransactionEnum, type TRPCContext, type TRPCContextTransaction } from "./TRPCContext" import { TRPCContextTransactionEnum, type TRPCContext, type TRPCContextTransaction } from "./TRPCContext"
@@ -55,13 +55,31 @@ export module TRPCContextCreator {
const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) => const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.sandbox(effect).pipe( Effect.sandbox(effect).pipe(
Effect.catchTags({ Effect.catchTags({
Die: cause => Effect.fail( Empty: cause => Effect.fail(
new TRPCError({ new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause), cause: new TRCPErrorCause(cause),
}) })
), ),
Fail: cause => Effect.fail(
cause.error instanceof TRPCError
? cause.error
: new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Die: cause => Effect.fail(
cause.defect instanceof TRPCError
? cause.defect
: new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Interrupt: cause => Effect.fail( Interrupt: cause => Effect.fail(
new TRPCError({ new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
@@ -69,14 +87,7 @@ const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
}) })
), ),
Fail: cause => Effect.fail( Sequential: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Empty: cause => Effect.fail(
new TRPCError({ new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause), cause: new TRCPErrorCause(cause),
@@ -89,19 +100,12 @@ const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
cause: new TRCPErrorCause(cause), cause: new TRCPErrorCause(cause),
}) })
), ),
Sequential: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
}) })
) )
export class TRCPErrorCause extends Error { export class TRCPErrorCause<E> extends Error {
constructor(readonly cause: unknown) { constructor(readonly cause: Cause.Cause<E>) {
super() super()
} }
} }