0.1.19 (#20)
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com> Reviewed-on: #20
This commit was merged in pull request #20.
This commit is contained in:
33
src/TRPC/middlewares/DecodeInput.ts
Normal file
33
src/TRPC/middlewares/DecodeInput.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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<any>
|
||||
input: I
|
||||
}>().create(
|
||||
async ({ ctx, input, next }) => next({
|
||||
ctx: { decodedInput: await ctx.run(decode(input)) } as const
|
||||
})
|
||||
)
|
||||
})
|
||||
Reference in New Issue
Block a user