34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
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 = <A, I>(
|
|
schema: Schema.Schema<A, I>,
|
|
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<never>
|
|
input: I
|
|
}>().create(
|
|
async ({ ctx, input, next }) => next({
|
|
ctx: { decodedInput: await ctx.run(decode(input)) } as const
|
|
})
|
|
)
|
|
})
|