diff --git a/lib/schema-controller.js b/lib/schema-controller.js index 78c4437678..8c746735ff 100644 --- a/lib/schema-controller.js +++ b/lib/schema-controller.js @@ -15,12 +15,16 @@ function buildSchemaController (parentSchemaCtrl, opts) { return new SchemaController(parentSchemaCtrl, opts) } - let compilersFactory = { - buildValidator: ValidatorSelector(), - buildSerializer: SerializerSelector() + const compilersFactory = Object.assign({ + buildValidator: null, + buildSerializer: null + }, opts?.compilersFactory) + + if (!compilersFactory.buildValidator) { + compilersFactory.buildValidator = ValidatorSelector() } - if (opts && opts.compilersFactory) { - compilersFactory = Object.assign(compilersFactory, opts.compilersFactory) + if (!compilersFactory.buildSerializer) { + compilersFactory.buildSerializer = SerializerSelector() } const option = { diff --git a/test/schema-special-usage.test.js b/test/schema-special-usage.test.js index 8f438c2721..1fc99dc618 100644 --- a/test/schema-special-usage.test.js +++ b/test/schema-special-usage.test.js @@ -702,3 +702,45 @@ test('Custom schema object should not trigger FST_ERR_SCH_DUPLICATE', async t => await fastify.ready() t.pass('fastify is ready') }) + +test('The default schema compilers should not be called when overwritte by the user', async t => { + const Fastify = t.mock('../', { + '@fastify/ajv-compiler': () => { + t.fail('The default validator compiler should not be called') + }, + '@fastify/fast-json-stringify-compiler': () => { + t.fail('The default serializer compiler should not be called') + } + }) + + const fastify = Fastify({ + schemaController: { + compilersFactory: { + buildValidator: function factory () { + t.pass('The custom validator compiler should be called') + return function validatorCompiler () { + return () => { return true } + } + }, + buildSerializer: function factory () { + t.pass('The custom serializer compiler should be called') + return function serializerCompiler () { + return () => { return true } + } + } + } + } + }) + + fastify.get('/', + { + schema: { + query: { foo: { type: 'string' } }, + response: { + 200: { type: 'object' } + } + } + }, () => {}) + + await fastify.ready() +})