Archived
2
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
definma-api/src/routes/validate/parameters.ts
2020-05-11 13:05:54 +02:00

35 lines
1.3 KiB
TypeScript

import Joi from '@hapi/joi';
export default class ParametersValidate {
static input (data, parameters, param) { // data to validate, parameters from template, param: 'new', 'change'
let joiObject = {};
parameters.forEach(parameter => {
if (parameter.range.hasOwnProperty('values')) {
joiObject[parameter.name] = Joi.alternatives()
.try(Joi.string(), Joi.number(), Joi.boolean())
.valid(...parameter.range.values);
}
else if (parameter.range.hasOwnProperty('min') && parameter.range.hasOwnProperty('max')) {
joiObject[parameter.name] = Joi.number()
.min(parameter.range.min)
.max(parameter.range.max);
}
else if (parameter.range.hasOwnProperty('min')) {
joiObject[parameter.name] = Joi.number()
.min(parameter.range.min);
}
else if (parameter.range.hasOwnProperty('max')) {
joiObject[parameter.name] = Joi.number()
.max(parameter.range.max);
}
else {
joiObject[parameter.name] = Joi.alternatives()
.try(Joi.string(), Joi.number(), Joi.boolean());
}
if (param === 'new') {
joiObject[parameter.name] = joiObject[parameter.name].required()
}
});
return Joi.object(joiObject).validate(data);
}
}