remix-params-helper
remix-params-helper copied to clipboard
SyntaxError when using zod `.preprocess()`
Describe the bug
SyntaxError when using zod .preprocess()
.
Schema seems to work correctly when using zod .parse()
. I noticed the same schema doesn't seem to be supported when used with getParamsOrFail()
.
Steps to Reproduce the Bug or Issue
const schema = z.object({
id: z.string(),
intervals: z.preprocess(
(val) => (typeof val === "string" ? JSON.parse(val) : []),
z.array(
z.object({
// id: z.number(),
day: z.number().min(0).max(6),
from: z.string().regex(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/),
to: z.string().regex(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/),
})
)
),
intervalIds: z.preprocess(
(val) => (typeof val === "string" ? JSON.parse(val) : []),
z.array(z.number())
),
});
const intervals = formData.get("intervals");
const intervalIds = formData.get("intervalIds");
console.log({ intervals, intervalIds });
// works ✅
const dataZod = schema.parse({ id: "test", intervals, intervalIds });
console.log({ dataZod });
// throws error 🔴
const data = await getParamsOrFail(formData, schema);
console.log({ data });
Output:
{
intervals: '[{"id":1,"day":1,"from":"07:00","to":"23:30"},{"id":2,"day":2,"from":"07:00","to":"23:30"},{"id":3,"day":3,"from":"07:00","to":"23:30"},{"id":4,"day":4,"from":"07:00","to":"23:30"},{"id":5,"day":5,"from":"07:00","to":"23:30"},{"id":6,"day":6,"from":"07:00","to":"23:30"}]',
intervalIds: '[1,2,3,4,5,6]'
}
{
dataZod: {
id: 'test',
intervals: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
intervalIds: [ 1, 2, 3, 4, 5, 6 ]
}
}
SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
Expected behavior
{
data: {
id: 'test',
intervals: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
intervalIds: [ 1, 2, 3, 4, 5, 6 ]
}
}
FYI, the root error is:
Error: Unexpected type ZodObject for key intervals
From what I read, I believe .preprocess()
is not supported (yet)?
https://github.com/kiliman/remix-params-helper/blob/76115b81a20f1779fec9bfe9f6ac37d4e02a8228/src/helper.ts#L206-L236
First param of .preprocess()
is a type coercion function:
https://github.com/colinhacks/zod#preprocess
I see. Looks like it's not handled properly. Thanks for your test case. I'll work to support it.
Thank you, I'm not quite sure how to handle this case, otherwise I would have tried to make a PR.