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 type { CreateExpressContextOptions } from "@trpc/server/adapters/express"
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 { TRPCContextTransactionEnum, type TRPCContext, type TRPCContextTransaction } from "./TRPCContext"
@@ -10,9 +10,9 @@ import { TRPCContextTransactionEnum, type TRPCContext, type TRPCContextTransacti
* Provides functions that instantiate a fresh context for each tRPC procedure call
*/
export class TRPCContextCreator extends Context.Tag("TRPCContextCreator")<TRPCContextCreator, {
createContext: (transaction: TRPCContextTransaction) => TRPCContext
createExpressContext: (context: CreateExpressContextOptions) => TRPCContext
createWebSocketContext: (context: CreateWSSContextFnOptions) => TRPCContext
createContext: (transaction: TRPCContextTransaction) => TRPCContext
createExpressContext: (context: CreateExpressContextOptions) => TRPCContext
createWebSocketContext: (context: CreateWSSContextFnOptions) => TRPCContext
}>() {}
export module TRPCContextCreator {
@@ -55,27 +55,6 @@ export module TRPCContextCreator {
const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.sandbox(effect).pipe(
Effect.catchTags({
Die: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Interrupt: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Fail: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
Empty: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
@@ -83,7 +62,25 @@ const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
})
),
Parallel: cause => Effect.fail(
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(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
@@ -96,12 +93,19 @@ const mapErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
cause: new TRCPErrorCause(cause),
})
),
Parallel: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRCPErrorCause(cause),
})
),
})
)
export class TRCPErrorCause extends Error {
constructor(readonly cause: unknown) {
export class TRCPErrorCause<E> extends Error {
constructor(readonly cause: Cause.Cause<E>) {
super()
}
}