1 | 'use strict'
|
2 |
|
3 | const Ajv = require('ajv')
|
4 | const fastJsonStringify = require('fast-json-stringify')
|
5 |
|
6 | function 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 |
|
27 | function ValidatorCompiler (externalSchemas, options, cache) {
|
28 |
|
29 |
|
30 | const ajv = new Ajv(Object.assign({
|
31 | coerceTypes: true,
|
32 | useDefaults: true,
|
33 | removeAdditional: true,
|
34 |
|
35 |
|
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 |
|
53 | function SerializerCompiler (externalSchemas) {
|
54 | return function ({ schema, method, url, httpStatus }) {
|
55 | return fastJsonStringify(schema, { schema: externalSchemas })
|
56 | }
|
57 | }
|
58 |
|
59 | module.exports.ValidatorCompiler = ValidatorCompiler
|
60 | module.exports.ValidatorSelector = ValidatorSelector
|
61 | module.exports.SerializerCompiler = SerializerCompiler
|