add config validation

This commit is contained in:
Josh Harvey 2017-04-21 02:10:44 +03:00
parent b9465a4cf9
commit d26ce117fd
2 changed files with 46 additions and 1 deletions

View file

@ -117,7 +117,15 @@
"enabledIf": [ "enabledIf": [
"cashOutEnabled" "cashOutEnabled"
], ],
"fieldValidation": [{"code": "required"}] "fieldValidation": [
{
"code": "required"
},
{
"code": "min",
"min": 0
}
]
}, },
{ {
"code": "lowBalanceMargin", "code": "lowBalanceMargin",

View file

@ -6,6 +6,11 @@ const argv = require('minimist')(process.argv.slice(2))
const pify = require('pify') const pify = require('pify')
const db = require('./db') const db = require('./db')
const options = require('./options')
const logger = require('./logger')
const schemaPath = path.resolve(options.lamassuServerPath, 'lamassu-schema.json')
const schema = require(schemaPath)
let settingsCache let settingsCache
@ -68,6 +73,7 @@ function loadConfig (versionId) {
return db.oneOrNone(sql, [versionId, 'config']) return db.oneOrNone(sql, [versionId, 'config'])
.then(row => row ? row.data.config : []) .then(row => row ? row.data.config : [])
.then(validate)
} }
function loadLatestConfig () { function loadLatestConfig () {
@ -81,6 +87,37 @@ function loadLatestConfig () {
return db.oneOrNone(sql, ['config']) return db.oneOrNone(sql, ['config'])
.then(row => row ? row.data.config : []) .then(row => row ? row.data.config : [])
.then(validate)
}
function checkConstraint (entry, constraint) {
switch (constraint.code) {
case 'min':
return entry.fieldValue.value >= constraint.min
default:
return true
}
}
function validateConstraint (entry, constraint) {
const isValid = checkConstraint(entry, constraint)
if (!isValid) logger.error(`Validation error: ${entry.fieldLocator.code} [${constraint.code}]`)
return isValid
}
function validateEntry (entry) {
const fieldCode = entry.fieldLocator.code
const schemaEntry = _.find(_.matchesProperty('code', fieldCode), schema.fields)
if (!schemaEntry) throw new Error(`Unsupported field: ${fieldCode}`)
const validations = schemaEntry.fieldValidation
return _.every(constraint => validateConstraint(entry, constraint), validations)
}
function validate (config) {
const isValid = _.every(validateEntry, config)
if (!isValid) throw new Error('Invalid config')
return config
} }
function loadAccounts () { function loadAccounts () {