fastify-zod-openapi icon indicating copy to clipboard operation
fastify-zod-openapi copied to clipboard

TypeError: Do not know how to serialize a BigInt

Open jsnimda opened this issue 1 year ago • 3 comments

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:

  1. Use any message for the ValidationError, I don't care it anyway?
  2. Use a library like safe-stable-stringify, which never throws, but this library will not preserve the order of object keys by default.
  3. Preserve the structure instead of stringifying it.
  4. 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!

jsnimda avatar Sep 24 '24 17:09 jsnimda

Happy to copy what fastify-type-provider-zod is doing: https://github.com/turkerdev/fastify-type-provider-zod/blob/main/src/ResponseValidationError.ts

samchungy avatar Sep 25 '24 00:09 samchungy

Will glad to see that😆

jsnimda avatar Sep 25 '24 01:09 jsnimda

@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...)

jsnimda avatar Sep 27 '24 15:09 jsnimda

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

samchungy avatar Oct 08 '24 23:10 samchungy