This starts the rewrite of the dynamic badges. I've pulled into BaseService an initial version of the query param validation from #2325. I've extended from BaseJsonService to avoid duplicating the deserialization logic, though it means there is a bit of duplicated code among the three dynamic services. The way to unravel this would be to move the logic from `_requestJson` and friends from the base classes into functions so DynamicJson can inherit from BaseDynamic. Would that be worth it? This introduces a regression of #1446 for this badge. Close #2345
51 lines
1.1 KiB
JavaScript
51 lines
1.1 KiB
JavaScript
'use strict'
|
|
|
|
const emojic = require('emojic')
|
|
const Joi = require('joi')
|
|
const trace = require('../services/trace')
|
|
|
|
function validate(
|
|
{
|
|
ErrorClass,
|
|
prettyErrorMessage = 'data does not match schema',
|
|
includeKeys = false,
|
|
traceErrorMessage = 'Data did not match schema',
|
|
traceSuccessMessage = 'Data after validation',
|
|
},
|
|
data,
|
|
schema
|
|
) {
|
|
if (!schema || !schema.isJoi) {
|
|
throw Error('A Joi schema is required')
|
|
}
|
|
const { error, value } = Joi.validate(data, schema, {
|
|
allowUnknown: true,
|
|
stripUnknown: true,
|
|
})
|
|
if (error) {
|
|
trace.logTrace(
|
|
'validate',
|
|
emojic.womanShrugging,
|
|
traceErrorMessage,
|
|
error.message
|
|
)
|
|
|
|
let prettyMessage = prettyErrorMessage
|
|
if (includeKeys) {
|
|
const keys = error.details.map(({ path }) => path)
|
|
if (keys) {
|
|
prettyMessage = `${prettyErrorMessage}: ${keys.join(',')}`
|
|
}
|
|
}
|
|
|
|
throw new ErrorClass({ prettyMessage, underlyingError: error })
|
|
} else {
|
|
trace.logTrace('validate', emojic.bathtub, traceSuccessMessage, value, {
|
|
deep: true,
|
|
})
|
|
return value
|
|
}
|
|
}
|
|
|
|
module.exports = validate
|