0

I'm looking for the best way to disable programmatically the json-schema validation for all routes in a fastify instance:

module.exports = async (fastify, opts) => {
  fastify.get('/stations.json', {schema: opts.schema}, async req => {
    return {
      ...
    };
  });
}

this is a working way:

  ...global config definitions...

  fastify.addHook('onRoute', route => {
    if (config.validation === false && route.schema) {
      route.schema = null
      console.log('Route disable:',route.path)
    }
  })

The problem with this solution is that it breaks fastify swagger-ui, instead I what simply to disable the validation in routes, keeping the schema definition for each one. I guess it could be done with the method: fastify.setValidatorCompiler() but I'm not very clear how I could use it. I would like to bypass executing validation functions in routes if possible, not just executing "empty functions".

3 Answers 3

2

The correct answer is:

fastify.setValidatorCompiler(() => () => true);

The {value: T} is designed for validation libraries that do transformations. So the answer with it would only work in this case:

fastify.setValidatorCompiler(() => {
  return (value) => ({ value });
  // ----^ notice that we get the value from args and return it
});

https://github.com/fastify/fastify/blob/816f852c56e229d3af4784b1a3705a50725c3f37/types/schema.d.ts#L35-L43

Sign up to request clarification or add additional context in comments.

2 Comments

please can you add some references in docs?
Added link to .d.ts
1

Based on fastify docs, validatorCompiler is a function that gets data, validate it and returns either {value: true/false} or {error: your error}.

setValidatorCompiler is a function that needs to return validatorCompiler (which is a function).

Therefore, you can set a validatorCompiler on the fastify instance, that will return always true.

const fastify = require('fastify')();

fastify.setValidatorCompiler(() => {
  return () => ({ value: true });
  // ----^ this is the validatorCompiler
});

I didn't tested this code, but, based on the docs page, it should work.

1 Comment

not working using {value:true} object
0

schema validation is done by ajv plugin which can be disabled by using the code below

 const fastify=require('fastify')
  ({
  ajv:{customOptions:{strict:false}}
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.