turkerdev / fastify-type-provider-zod

MIT License
386 stars 24 forks source link

handler error when trying to send json #84

Open netgfx opened 4 months ago

netgfx commented 4 months ago

I have a weird issue were the handler function if set to return a json object like {success: "ok"} it throws error

"Cannot read properties of undefined (reading 'length')"

I implement it like this:

fastify.withTypeProvider().route({
    method: 'POST',
    url: '/login',
    // Define your schema
    schema: {
      body: REGISTER_SCHEMA,
      response: {
        200: z.object({success: z.boolean()}),
      },
    },
    handler: (req, res) => {
      req.session.set('user', 'user-data');
      res.send({success: 'ok'});
    },
  });

nothing special.

Isn't res the same as the fastify reply in terms of capabilities? The request header content-type is set to 'application/json'

kibertoad commented 4 months ago

I will take a look this week!

JonRC commented 3 months ago

In the code above there are maybe two errors

  1. It's not passing ZodTypeProvider for withTypeProvider as generic.
  2. It's not passing the correct type to res.send, as defined in schema it should be a boolean but a string is being passed.

Could you fix these points and verify if have the same problem?

Here is a fix suggestion:

fastify.withTypeProvider<ZodTypeProvider>().route({
    method: 'POST',
    url: '/login',
    // Define your schema
    schema: {
      body: REGISTER_SCHEMA,
      response: {
        200: z.object({success: z.boolean()}),
      },
    },
    handler: (req, res) => {
      req.session.set('user', 'user-data');
      res.send({success: true});
    },
  });