Files
thilalib/src/TRPC/middlewares/DecodeInput.ts
Julien Valverdé 0312565b52
All checks were successful
Lint / lint (push) Successful in 12s
Fix
2024-09-08 23:23:04 +02:00

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
})
)
})