TypeError: Do not know how to serialize a BigInt
Hi, I am currently working on a tool that automatically converts querystring types based on a schema. However, I encounter an error with this example:
File: node_modules/fastify-zod-openapi/dist/index.mjs
18: class ValidationError extends Error {
19: constructor(zodError, httpPart) {
20: super(
21: httpPart ? JSON.stringify({
^^^^ TypeError: Do not know how to serialize a BigInt
22: [httpPart]: zodError.issues
23: }) : zodError.message
24: );
25: this.zodError = zodError;
26: this.httpPart = httpPart;
27: }
28: }
Minimal reproducible example
const fastify = Fastify().withTypeProvider<FastifyZodOpenApiTypeProvider>();
fastify.setValidatorCompiler(validatorCompiler);
fastify.setSerializerCompiler(serializerCompiler);
fastify.get('/example', {
schema: {
querystring: z.object({
a: z.preprocess((val) => {
try {
if (typeof val === 'string') return BigInt(val);
return val;
} catch (e) {
return val;
}
}, z.literal(BigInt('42'))),
}),
},
}, (request, reply) => reply.send({ success: true }));
const response = await fastify.inject({
method: 'GET',
url: '/example?a=43',
});
Response:
{"statusCode":500,"error":"Internal Server Error","message":"Do not know how to serialize a BigInt"}
I have some possible suggestions, maybe:
- Use any message for the ValidationError, I don't care it anyway?
- Use a library like
safe-stable-stringify, which never throws, but this library will not preserve the order of object keys by default. - Preserve the structure instead of stringifying it.
- Any other methods I might not be aware of? 🤔
If you have any comments, please let me know. I'm good with any solution as long as it doesn't throw an error. Thanks!
Happy to copy what fastify-type-provider-zod is doing: https://github.com/turkerdev/fastify-type-provider-zod/blob/main/src/ResponseValidationError.ts
Will glad to see that😆
@samchungy I expect I will see a 400 error instead of 500 for my above schema, will there a fix? Sure I can do a PR with a simple fix, just replacing the above JSON.stringify to stringify from safe-stable-stringify for a minimal change. That package is what fastify is using (fastify use pino, pino use safe-stable-stringify, etc...)
I think a new error type would probably be more ideal in truth, sorry I'm a little stretched for time but will hop on this soon