Open potados99 opened 3 years ago
I'd do it like this:
import { z } from "zod"
// copy of the private Zod utility type of ZodObject
type UnknownKeysParam = "passthrough" | "strict" | "strip"
type TQuery<U extends UnknownKeysParam = any> =
| z.ZodObject<any, U>
| z.ZodUnion<[TQuery<U>, ...TQuery<U>[]]>
| z.ZodIntersection<TQuery<U>, TQuery<U>>
| z.ZodDiscriminatedUnion<string, z.Primitive, z.ZodObject<any, U>>;
export const validateRequestQuery: <TQ extends TQuery>(
zodSchema: TQ,
) => RequestHandler<ParamsDictionary, any, any, TQ> = (schema) => (req, res, next) => {
const parsed = schema.safeParse(req.query);
if (parsed.success) {
return next();
} else {
return sendErrors([{ type: 'Query', errors: parsed.error }], res);
}
};
@wobsoriano Thanks! I'll try it.
Casting through unknown
helps me :
z.string()
.transform(Number)
.pipe(z.number().int().positive()) as unknown as z.ZodNumber
Example below works:
However, when I add
.transform()
to thenum
, thevalidateRequestParams()
refuses to take the schema:It gives me this error:
I managed to solve it by modifying the
RequestValidation
type:The error is resolved, but not sure if it is the best way to handle it. Any suggestions?