-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.js
More file actions
54 lines (48 loc) · 2.15 KB
/
Copy pathcompiler.js
File metadata and controls
54 lines (48 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict'
const { Validator } = require('ata-validator')
// @fastify/ajv-compiler-compatible factory so ata can be installed as
// Fastify's global default validator:
//
// Fastify({ schemaController: { compilersFactory: { buildValidator: AtaCompiler() } } })
//
// Shape mirrors @fastify/ajv-compiler:
// AtaCompiler() -> buildCompilerFromPool(externalSchemas, options)
// -> buildValidatorFunction({ schema }) -> validate(data)
function AtaCompiler() {
return function buildCompilerFromPool(externalSchemas, options) {
const customOptions = (options && options.customOptions) || {}
// Default to Fastify's default AJV behavior: coerce (array mode, so a scalar
// becomes a single-element array), apply defaults, strip undeclared
// properties. Honor explicit overrides, preserving the 'array' mode value.
const coerceTypes = customOptions.coerceTypes !== undefined ? customOptions.coerceTypes : 'array'
const removeAdditional = customOptions.removeAdditional !== undefined ? !!customOptions.removeAdditional : true
// Fastify's default AJV runs with allErrors: false, reporting only the
// first violation. Mirror that unless the caller opts into allErrors. ata's
// abortEarly returns a stub error, so instead collect fully and expose the
// first real error to keep its message and rich fields intact.
const firstErrorOnly = customOptions.allErrors !== true
const hasCoercion = coerceTypes || removeAdditional
const validatorOpts = {
schemas: externalSchemas,
coerceTypes,
removeAdditional,
}
return function buildValidatorFunction({ schema }) {
const validator = new Validator(schema, validatorOpts)
function validate(data) {
const result = validator.validate(data)
if (result.valid) {
validate.errors = null
return hasCoercion ? { value: data } : true
}
validate.errors = firstErrorOnly ? [result.errors[0]] : result.errors
return false
}
validate.errors = null
return validate
}
}
}
module.exports = AtaCompiler
module.exports.AtaCompiler = AtaCompiler
module.exports.default = AtaCompiler