fastify / help

Need help with Fastify? File an Issue here.
https://www.fastify.io/
65 stars 8 forks source link

Help - Configure setValidatorCompiler in Typescript #1065

Open itizarsa opened 5 days ago

itizarsa commented 5 days ago

💬 Question here

Following docs, I'm trying to setValidatorCompiler like

const schemaCompilers: Record<string, Ajv.Ajv> = {
    body: new Ajv({
        removeAdditional: 'all',
        useDefaults: true,
        coerceTypes: false,
        addUsedSchema: false,
        allErrors: false,
    }),
    others: new Ajv({
        removeAdditional: 'all',
        useDefaults: true,
        coerceTypes: 'array',
        addUsedSchema: false,
        allErrors: false,
    }),
};

server.setValidatorCompiler((req) => {
    if (!req.httpPart) {
        throw new Error('Missing httpPart');
    }
    const compiler = schemaCompilers[req.httpPart] || schemaCompilers['others'];
    if (!compiler) {
        throw new Error(`Missing compiler for ${req.httpPart}`);
    }

    return compiler.compile(req.schema);
});

But I'm getting the below typescript error

Argument of type '(req: FastifyRouteSchemaDef<FastifySchema>) => ValidateFunction' is not assignable to parameter of type 'FastifySchemaCompiler<FastifySchema>'.
  Call signature return types 'ValidateFunction' and 'FastifyValidationResult' are incompatible.
    The types of 'errors' are incompatible between these types.
      Type 'ErrorObject[] | null | undefined' is not assignable to type 'FastifySchemaValidationError[] | null | undefined'.
        Type 'ErrorObject[]' is not assignable to type 'FastifySchemaValidationError[]'.
          Property 'instancePath' is missing in type 'ErrorObject' but required in type 'FastifySchemaValidationError'.

How do I setup different compilers for schema validation?

PS: I don't want to coerce the body json, which is why I'm trying to setup different compilers.

Your Environment

mcollina commented 5 days ago

Thanks for reporting!

Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.

itizarsa commented 4 days ago

@mcollina I couldn't reproduce it with a minimal example. I just found that it happens when I use Fastify on the nx mono repo. I'll try to share a reproducible repo.

itizarsa commented 4 days ago

@mcollina I found the problem to be with the ajv version. For some reason, Eslint is using ajv 6, which conflicts with Fastify ajv 8. I don't know how dependencies are resolved. Due to this typescript is having a tough time picking the correct type.

itizarsa commented 4 days ago

I'm not sure how to solve this too 😕

itizarsa commented 4 days ago

Repo - https://github.com/itizarsa/fastify