import { Schema } from "@effect/schema" import type { ParseOptions } from "@effect/schema/AST" import { Effect } from "effect" import { importTRPCServer } from "../importTRPCServer" import type { TRPCContextRuntime } from "../TRPCContext" export const DecodeInput = ( schema: Schema.Schema, options?: ParseOptions, ) => Effect.gen(function*() { const { experimental_standaloneMiddleware, TRPCError } = yield* importTRPCServer const decode = (value: I) => Schema.decode(schema, options)(value).pipe( Effect.matchEffect({ onSuccess: Effect.succeed, onFailure: e => Effect.fail(new TRPCError({ code: "BAD_REQUEST", message: "Could not decode input", cause: e, })), }) ) return experimental_standaloneMiddleware<{ ctx: TRPCContextRuntime input: I }>().create( async ({ ctx, input, next }) => next({ ctx: { decodedInput: await ctx.run(decode(input)) } as const }) ) })