-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (51 loc) · 1.67 KB
/
Copy pathindex.js
File metadata and controls
58 lines (51 loc) · 1.67 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
55
56
57
58
'use strict'
const fp = require('fastify-plugin')
const { Validator } = require('ata-validator')
function prettyFormat(errors, dataVar) {
const message = errors.map((e) => {
let line = `${dataVar}${e.instancePath || ''} ${e.message}`
if (e.code) line += ` [${e.code}]`
if (e.suggestion && e.suggestion.text) line += ` (${e.suggestion.text})`
return line
}).join(', ')
const err = new Error(message)
err.statusCode = 400
return err
}
function fastifyAta(fastify, opts, done) {
const cache = new WeakMap()
const hasCoercion = !!(opts.coerceTypes || opts.removeAdditional)
const validatorOpts = {
coerceTypes: opts.coerceTypes || false,
removeAdditional: opts.removeAdditional || false,
abortEarly: opts.abortEarly || false,
}
if (opts.prettyErrors) {
fastify.setSchemaErrorFormatter(prettyFormat)
}
fastify.setValidatorCompiler(({ schema }) => {
let validator = cache.get(schema)
if (!validator) {
// Pass schemas registered via `fastify.addSchema` so cross-schema `$ref`
// (e.g. `{ $ref: 'shared#' }`) resolves. Compilers run at ready() time,
// after every addSchema, so getSchemas() returns the full bucket.
validator = new Validator(schema, { ...validatorOpts, schemas: fastify.getSchemas() })
cache.set(schema, validator)
}
const validate = (data) => {
const result = validator.validate(data)
if (result.valid) {
return hasCoercion ? { value: data } : true
}
validate.errors = result.errors
return false
}
validate.errors = null
return validate
})
done()
}
module.exports = fp(fastifyAta, {
fastify: '>=4.0.0',
name: 'fastify-ata',
})