2019-06-17 20:21:45 +10:00
|
|
|
const path = require('path');
|
|
|
|
const fs = require('fs');
|
2020-01-21 17:36:46 +10:00
|
|
|
const moment = require('moment');
|
2019-07-11 15:35:03 +10:00
|
|
|
const glob = require('glob');
|
2019-11-16 09:01:57 +10:00
|
|
|
const Ajv = require('ajv');
|
2020-03-17 18:38:46 +10:00
|
|
|
const ajv = new Ajv({ allErrors: true, jsonPointers: true });
|
2019-06-17 20:21:45 +10:00
|
|
|
|
|
|
|
const addSchemas = () => {
|
2019-07-11 15:35:03 +10:00
|
|
|
const schemaFiles = glob.sync('./lib/**/*.json');
|
2019-11-16 09:01:57 +10:00
|
|
|
schemaFiles.forEach((file) => {
|
2019-06-17 20:21:45 +10:00
|
|
|
const fileData = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
2019-11-16 09:01:57 +10:00
|
|
|
ajv.addSchema(fileData, path.basename(file, '.json'));
|
2019-06-17 20:21:45 +10:00
|
|
|
});
|
2019-11-16 12:22:54 +10:00
|
|
|
|
|
|
|
// Email format
|
|
|
|
const emailRegex = /^([\w-.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
|
|
|
|
ajv.addFormat('emailAddress', emailRegex);
|
|
|
|
|
|
|
|
// Amount format
|
2020-01-08 18:28:29 +10:00
|
|
|
const amountRegex = /^\d+\.\d\d$/;
|
2019-11-16 12:22:54 +10:00
|
|
|
ajv.addFormat('amount', amountRegex);
|
2019-11-16 20:57:48 +10:00
|
|
|
|
2020-01-21 17:36:46 +10:00
|
|
|
// Datetime format
|
|
|
|
ajv.addFormat('datetime', {
|
|
|
|
validate: (dateTimeString) => {
|
|
|
|
return moment(dateTimeString, 'DD/MM/YYYY HH:mm').isValid();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2019-11-16 20:57:48 +10:00
|
|
|
ajv.addKeyword('isNotEmpty', {
|
2020-03-17 18:38:46 +10:00
|
|
|
validate: function validate(schema, data){
|
|
|
|
const result = typeof data === 'string' && data.trim() !== '';
|
|
|
|
if(!result){
|
|
|
|
console.log('result', result);
|
|
|
|
validate.errors = [{ keyword: 'isNotEmpty', message: 'Cannot be an empty string', params: { keyword: 'isNotEmpty' } }];
|
|
|
|
}
|
|
|
|
return result;
|
2019-11-16 20:57:48 +10:00
|
|
|
},
|
2020-03-17 18:38:46 +10:00
|
|
|
errors: true
|
2019-11-16 20:57:48 +10:00
|
|
|
});
|
2020-03-17 18:38:46 +10:00
|
|
|
|
|
|
|
require('ajv-errors')(ajv);
|
2019-06-17 20:21:45 +10:00
|
|
|
};
|
|
|
|
|
|
|
|
const validateJson = (schema, json) => {
|
2019-11-16 12:22:54 +10:00
|
|
|
const result = ajv.validate(schema, json);
|
2020-02-21 12:21:56 +10:00
|
|
|
return {
|
2019-11-16 12:22:54 +10:00
|
|
|
result,
|
|
|
|
errors: ajv.errors
|
|
|
|
};
|
2019-06-17 20:21:45 +10:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
addSchemas,
|
|
|
|
validateJson
|
|
|
|
};
|