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

35 lines
1.3 KiB
TypeScript
Raw Normal View History

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