Files
thilalib/src/TRPC/TRPCContextCreator.ts
Julien Valverdé 253c3ec00d
All checks were successful
Lint / lint (push) Successful in 12s
TRPCContextCreator refactoring
2024-09-07 05:15:19 +02:00

58 lines
2.4 KiB
TypeScript

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 const Identifier = "@thilalib/TRPC/TRPCContextCreator"
export interface TRPCContextCreator<R> extends Context.Tag<typeof Identifier, TRPCContextCreatorService<R>> {}
export interface TRPCContextCreatorService<R> {
readonly createContext: (transaction: TRPCContextTransaction) => TRPCContext<R>
readonly createExpressContext: (context: CreateExpressContextOptions) => TRPCContext<R>
readonly createWebSocketContext: (context: CreateWSSContextFnOptions) => TRPCContext<R>
}
export const TRPCUnknownContextCreator = Context.GenericTag<typeof Identifier, TRPCContextCreatorService<unknown>>(Identifier)
export const make = <R>() => {
const TRPCContextCreator = Context.GenericTag<typeof Identifier, TRPCContextCreatorService<R>>(Identifier)
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 } as const
}