fastify / fastify-auth

Run multiple auth functions in Fastify
Other
341 stars 56 forks source link

Type definitions as defined in the route schema get removed when using fastify auth #222

Closed mapokapo closed 6 months ago

mapokapo commented 6 months ago

Prerequisites

Fastify version

4.0.0

Plugin version

4.5.0

Node.js version

18.18.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Fedora 39

Description

When you define a body schema in the fastify route options, you get Typescript type completion in the handler function. However, adding the fastify auth function to the onRequest or preHandler hook removes these definitions, and makes body of type unknown.

Steps to Reproduce

Take the following route for example:

fastify.route({
    method: "POST",
    url: "/",
    schema: {
      body: CreateTodo,
      response: {
        201: ReturnTodo,
      },
    },
    onRequest: fastify.auth([fastify.verifyJWT]),
    handler: async ({ body }, reply) => {
      const result = await fastify.prisma.todo.create({ data: body }); // error here: "body is of type `unknown`"
      const todo = {
        ...result,
        createdAt: result.createdAt.toISOString(),
        updatedAt: result.updatedAt.toISOString(),
      };

      reply.code(201);
      return todo;
    },
  });

However, when we remove the onRequest hook, the error disappears.

Expected Behavior

The type definitions from the schema should carry on through the hook where the fastify auth function is used, and should apply to the actual handler function.

climba03003 commented 6 months ago

Duplicate of #207

climba03003 commented 6 months ago

You may try the master branch here to see if the problem solved.