yonathan06 / fastify-now

File based routing for fastify https://github.com/fastify/fastify
MIT License
72 stars 8 forks source link

Unable to use `@sinclair/typebox` #24

Closed 0xMukesh closed 2 years ago

0xMukesh commented 2 years ago

Hey! I'm trying to use typebox along with fastify-now, but I'm facing errors while doing so.

  1. I have installed and imported the @fastify/type-provider-typebox library

  2. I have configured the type-provider which would be used globally

    const server = fastify({
      logger: process.env.NODE_ENV === "development",
    })
      .setValidatorCompiler(TypeBoxValidatorCompiler)
      .withTypeProvider<TypeBoxTypeProvider>();
  3. I have imported @sinclair/typebox to my route file and added the schema via:

    POST.opts = {
      schema: {
        body: Type.Object({
          name: Type.String({
            description: "Name of the user",
          }),
          email: Type.String({
            description: "Email of the user",
          }),
        }),
        headers: Type.Object({
          authorization: Type.String({
            description: "Admin API key of CandyPay's public API",
          }),
        }),
      },
    };

    When I try to run the application, I face this error:

    FastifyError [Error]: Failed building the validation schema for POST: /api/v1/api-key, due to error TypeGuard: Invalid type
yonathan06 commented 2 years ago

I never tried using it with @fastify/type-provider-typebox and @sinclair/typebox, so not sure what is the source of the error. Can you try wrapping your Type.Object with Type.Strict? so it will be:

POST.opts = {
  schema: {
    body: Type.Strict(Type.Object({
      name: Type.String({
        description: "Name of the user",
      }),
      email: Type.String({
        description: "Email of the user",
      }),
    })),
  },
};
0xMukesh commented 2 years ago

@yonathan06 Have tried it out, still the same error

0xMukesh commented 2 years ago

Is there any kind of way to integrate other input-validation library such as zod to fastify-now?

yonathan06 commented 2 years ago

not sure if that is a fastify-now issue, does your code work with a regular route using register() function?

0xMukesh commented 2 years ago

Hey! I have figured out the issue, was a mistake from my side. Thanks for pointing me towards the solution 😄