expressCart/lib/schema.js

35 lines
912 B
JavaScript
Raw Normal View History

const path = require('path');
const fs = require('fs');
2019-07-11 15:35:03 +10:00
const glob = require('glob');
2019-11-16 09:01:57 +10:00
const Ajv = require('ajv');
const ajv = new Ajv();
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) => {
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-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
const amountRegex = /^[1-9]\d*(\.\d+)?$/;
ajv.addFormat('amount', amountRegex);
};
const validateJson = (schema, json) => {
2019-11-16 12:22:54 +10:00
const result = ajv.validate(schema, json);
return{
result,
errors: ajv.errors
};
};
module.exports = {
addSchemas,
validateJson
};