turkerdev / fastify-type-provider-zod

MIT License
337 stars 21 forks source link

response : { 200: z.string() results in application/json response #35

Open Twiggeh opened 1 year ago

Twiggeh commented 1 year ago

Basically the title, when defining a route and if you put on

    schema: {
        response: { 200: z.string().optional() },
    }

results in 20221215_03h39m49s_grim

should be text/plain

Why this is important:

Autogenerated clients from the swagger docs will try to parse the output which will of course fail.

RodriguesCosta commented 1 year ago

To be able to change the response type we must define the produces field within the schema.


await app.route({
  method: 'GET',
  url: '/public-key',
  config: {
    rateLimit: {
      max: 4,
      timeWindow: '10s',
    },
  },
  schema: {
    tags: ['Base'],
    produces: ['text/plain'],
    response: {
      200: z.string(),
    },
  },
  handler: (request, reply) => {
    reply.send(authConfig.jwt.publicKey);
  },
});
Twiggeh commented 1 year ago

I am slightly confused here, wouldn't it be better if it would auto-infer that it is at least a text/ vs a application/json ?

Because if you later then generate a cient from the swagger the client usually adds a JSON.parse(), which throws an error on basic text

RodriguesCosta commented 1 year ago

I believe you are right, I am working on a pull request that will add the possibility of using @anatine/zod-openapi together with this plugin, I will see if I can solve it together with this pull request.