Files
todo-tests/packages/server/src/trpc/TRPCContextCreator.ts
2024-07-06 03:37:11 +02:00

45 lines
1.3 KiB
TypeScript

import { TRPCError } from "@trpc/server"
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express"
import { Context, Effect, Layer, Runtime } from "effect"
import type { Services } from "../Services"
import type { TRPCContext } from "./TRPCContext"
/**
* Provides a function that instantiates a fresh context for each tRPC procedure call
*/
export class TRPCContextCreator extends Context.Tag("TRPCContextCreator")<TRPCContextCreator,
(opts: CreateExpressContextOptions) => TRPCContext
>() {}
export module TRPCContextCreator {
export const Live = Layer.effect(TRPCContextCreator, Effect.gen(function*() {
const runtime = yield* Effect.runtime<Services>()
const run = Runtime.runPromise(runtime)
return ({ req }) => ({
runtime,
run,
req,
})
}))
}
const mapEffectErrorsToTRPC = <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" })
),
Interrupt: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR" })
),
Fail: cause => Effect.fail(
new TRPCError({ code: "INTERNAL_SERVER_ERROR" })
),
})
)