This commit is contained in:
55
src/Layers/trpc/TRPCContextCreator.ts
Normal file
55
src/Layers/trpc/TRPCContextCreator.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express"
|
||||
import type { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws"
|
||||
import { Context, Effect, Layer, Runtime } from "effect"
|
||||
import { createTRCPErrorMapper } from "./createTRCPErrorMapper"
|
||||
import { TRPCContextTransactionEnum, type TRPCContext, type TRPCContextTransaction } from "./TRPCContext"
|
||||
|
||||
|
||||
export { TRPCErrorCause } from "./createTRCPErrorMapper"
|
||||
export { TRPCContextTransactionEnum } from "./TRPCContext"
|
||||
export type { TRPCContext, TRPCContextTransaction } from "./TRPCContext"
|
||||
|
||||
|
||||
export const makeService = <R>() => {
|
||||
class TRPCContextCreator extends Context.Tag("TRPCContextCreator")<TRPCContextCreator, {
|
||||
readonly createContext: (transaction: TRPCContextTransaction) => TRPCContext<R>
|
||||
readonly createExpressContext: (context: CreateExpressContextOptions) => TRPCContext<R>
|
||||
readonly createWebSocketContext: (context: CreateWSSContextFnOptions) => TRPCContext<R>
|
||||
}>() {}
|
||||
|
||||
const TRPCContextCreatorLive = Layer.effect(TRPCContextCreator, Effect.gen(function*() {
|
||||
const runtime = yield* Effect.runtime<R>()
|
||||
const mapErrors = yield* createTRCPErrorMapper
|
||||
|
||||
const run = <A, E>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
) => Runtime.runPromise(runtime)(
|
||||
effect.pipe(mapErrors),
|
||||
options,
|
||||
)
|
||||
|
||||
const fork = <A, E>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
options?: Runtime.RunForkOptions,
|
||||
) => Runtime.runFork(runtime)(
|
||||
effect.pipe(mapErrors),
|
||||
options,
|
||||
)
|
||||
|
||||
|
||||
const createContext = (transaction: TRPCContextTransaction) => ({
|
||||
runtime,
|
||||
run,
|
||||
fork,
|
||||
transaction,
|
||||
})
|
||||
|
||||
const createExpressContext = (context: CreateExpressContextOptions) => createContext(TRPCContextTransactionEnum.Express(context))
|
||||
const createWebSocketContext = (context: CreateWSSContextFnOptions) => createContext(TRPCContextTransactionEnum.WebSocket(context))
|
||||
|
||||
return { createContext, createExpressContext, createWebSocketContext }
|
||||
}))
|
||||
|
||||
return { TRPCContextCreator, TRPCContextCreatorLive }
|
||||
}
|
||||
Reference in New Issue
Block a user