UNPKG

1.76 kBJavaScriptView Raw
1'use strict'
2
3const Ajv = require('ajv')
4const fastJsonStringify = require('fast-json-stringify')
5
6function ValidatorSelector () {
7 const validatorPool = new Map()
8 const cache = new Map()
9 cache.put = cache.set
10
11 return function buildCompilerFromPool (externalSchemas, options) {
12 const externals = JSON.stringify(externalSchemas)
13 const ajvConfig = JSON.stringify(options.customOptions)
14
15 const uniqueAjvKey = `${externals}${ajvConfig}`
16 if (validatorPool.has(uniqueAjvKey)) {
17 return validatorPool.get(uniqueAjvKey)
18 }
19
20 const compiler = ValidatorCompiler(externalSchemas, options, cache)
21 validatorPool.set(uniqueAjvKey, compiler)
22
23 return compiler
24 }
25}
26
27function ValidatorCompiler (externalSchemas, options, cache) {
28 // This instance of Ajv is private
29 // it should not be customized or used
30 const ajv = new Ajv(Object.assign({
31 coerceTypes: true,
32 useDefaults: true,
33 removeAdditional: true,
34 // Explicitly set allErrors to `false`.
35 // When set to `true`, a DoS attack is possible.
36 allErrors: false,
37 nullable: true
38 }, options.customOptions, { cache }))
39
40 if (options.plugins && options.plugins.length > 0) {
41 for (const plugin of options.plugins) {
42 plugin[0](ajv, plugin[1])
43 }
44 }
45
46 Object.values(externalSchemas).forEach(s => ajv.addSchema(s))
47
48 return ({ schema, method, url, httpPart }) => {
49 return ajv.compile(schema)
50 }
51}
52
53function SerializerCompiler (externalSchemas) {
54 return function ({ schema, method, url, httpStatus }) {
55 return fastJsonStringify(schema, { schema: externalSchemas })
56 }
57}
58
59module.exports.ValidatorCompiler = ValidatorCompiler
60module.exports.ValidatorSelector = ValidatorSelector
61module.exports.SerializerCompiler = SerializerCompiler