javascriptnode.jsfastify

Fastify disable schema validation


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".


Solution

  • 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