UNPKG

3.01 kBJavaScriptView Raw
1'use strict'
2
3const Ajv = require('ajv')
4const fs = require('fs')
5const path = require('path')
6const pack = require('ajv-pack')
7
8const ajv = new Ajv({
9 sourceCode: true, // this option is required by ajv-pack
10 removeAdditional: true,
11 useDefaults: true,
12 coerceTypes: true
13})
14
15const defaultInitOptions = {
16 bodyLimit: 1024 * 1024, // 1 MiB
17 caseSensitive: true,
18 disableRequestLogging: false,
19 ignoreTrailingSlash: false,
20 maxParamLength: 100,
21 onProtoPoisoning: 'error',
22 // TODO v3: default should be 'error'
23 onConstructorPoisoning: 'ignore',
24 pluginTimeout: 10000,
25 requestIdHeader: 'request-id',
26 requestIdLogLabel: 'reqId',
27 http2SessionTimeout: 5000
28}
29
30function customRule0 (schemaParamValue, validatedParamValue, validationSchemaObject, currentDataPath, validatedParamObject, validatedParam) {
31 validatedParamObject[validatedParam] = schemaParamValue
32 return true
33}
34
35// We add a keyword that allow us to set default values
36ajv.addKeyword('setDefaultValue', {
37 modifying: true,
38 validate: customRule0,
39 errors: false
40})
41
42const schema = {
43 type: 'object',
44 additionalProperties: false,
45 properties: {
46 bodyLimit: { type: 'integer', default: defaultInitOptions.bodyLimit },
47 caseSensitive: { type: 'boolean', default: defaultInitOptions.caseSensitive },
48 http2: { type: 'boolean' },
49 https: {
50 if: {
51 not: {
52 oneOf: [
53 { type: 'boolean' },
54 { type: 'null' },
55 {
56 type: 'object',
57 additionalProperties: false,
58 required: ['allowHTTP1'],
59 properties: {
60 allowHTTP1: { type: 'boolean' }
61 }
62 }
63 ]
64 }
65 },
66 then: { setDefaultValue: true }
67 },
68 ignoreTrailingSlash: { type: 'boolean', default: defaultInitOptions.ignoreTrailingSlash },
69 disableRequestLogging: {
70 type: 'boolean',
71 default: false
72 },
73 maxParamLength: { type: 'integer', default: defaultInitOptions.maxParamLength },
74 onProtoPoisoning: { type: 'string', default: defaultInitOptions.onProtoPoisoning },
75 onConstructorPoisoning: { type: 'string', default: defaultInitOptions.onConstructorPoisoning },
76 pluginTimeout: { type: 'integer', default: defaultInitOptions.pluginTimeout },
77 requestIdHeader: { type: 'string', default: defaultInitOptions.requestIdHeader },
78 requestIdLogLabel: { type: 'string', default: defaultInitOptions.requestIdLogLabel },
79 http2SessionTimeout: { type: 'integer', default: defaultInitOptions.http2SessionTimeout }
80 }
81}
82
83const validate = ajv.compile(schema)
84
85const moduleCode = `// This file is autogenerated by ${__filename.replace(__dirname, 'build')}, do not edit
86/* istanbul ignore file */
87// constant needed for customRule0 to work
88const self = {}
89
90${pack(ajv, validate)}
91
92${customRule0.toString()}
93
94module.exports.defaultInitOptions = ${JSON.stringify(defaultInitOptions)}
95`
96
97fs.writeFileSync(path.join(__dirname, '..', 'lib', 'configValidator.js'), moduleCode)