|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const path = require('node:path') |
| 4 | +const Ajv = require('ajv') |
| 5 | +const addFormats = require('ajv-formats') |
| 6 | +const cronValidate = require('cron-validate') |
| 7 | +const cron = cronValidate.default ?? cronValidate |
| 8 | +const { validateStrict } = require('compare-versions') |
| 9 | + |
| 10 | +const isDevEnv = process.env.NODE_ENV === 'development' |
| 11 | + |
| 12 | +const SCHEMA_IDS = require('./schema.ids') |
| 13 | +const schemas = require('./schemas') |
| 14 | +const { |
| 15 | + DataValidationSchemaDefError, |
| 16 | + DataValidationError |
| 17 | +} = require('../../errors') |
| 18 | + |
| 19 | +const ajv = new Ajv({ |
| 20 | + // Compile schema on initialization |
| 21 | + schemas, |
| 22 | + |
| 23 | + // Strict mode |
| 24 | + strict: true, |
| 25 | + strictRequired: true, |
| 26 | + allowMatchingProperties: true, |
| 27 | + allowUnionTypes: true, |
| 28 | + |
| 29 | + coerceTypes: true, |
| 30 | + useDefaults: 'empty', |
| 31 | + removeAdditional: true, |
| 32 | + $data: true, |
| 33 | + ownProperties: true, |
| 34 | + allErrors: true, |
| 35 | + messages: true, |
| 36 | + formats: { reserved: true }, |
| 37 | + verbose: isDevEnv |
| 38 | +}) |
| 39 | +addFormats(ajv) |
| 40 | +ajv.addFormat('abs-path', { |
| 41 | + type: 'string', |
| 42 | + validate: (val) => path.isAbsolute(val) |
| 43 | +}) |
| 44 | +ajv.addFormat('cron-expression', { |
| 45 | + type: 'string', |
| 46 | + validate: (val) => cron(val).isValid() |
| 47 | +}) |
| 48 | +ajv.addFormat('semver', { |
| 49 | + type: 'string', |
| 50 | + validate: (val) => validateStrict(val) |
| 51 | +}) |
| 52 | + |
| 53 | +const validate = (configs, schemaId) => { |
| 54 | + const validate = ajv.getSchema(schemaId) |
| 55 | + |
| 56 | + if (typeof validate !== 'function') { |
| 57 | + console.error(new DataValidationSchemaDefError()) |
| 58 | + |
| 59 | + return false |
| 60 | + } |
| 61 | + |
| 62 | + const res = validate(configs) |
| 63 | + |
| 64 | + if (validate.errors) { |
| 65 | + console.debug(new DataValidationError({ |
| 66 | + message: `ERR_DATA_IS_INVALID_WITH_ID: ${schemaId}`, |
| 67 | + data: validate.errors |
| 68 | + })) |
| 69 | + } |
| 70 | + |
| 71 | + return res |
| 72 | +} |
| 73 | + |
| 74 | +module.exports = { |
| 75 | + SCHEMA_IDS, |
| 76 | + validate |
| 77 | +} |
0 commit comments