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/template.ts

104 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-05-04 15:48:07 +02:00
import joi from '@hapi/joi';
import IdValidate from './id';
export default class TemplateValidate {
private static template = {
name: joi.string()
.max(128),
2020-05-14 12:31:57 +02:00
version: joi.number()
.min(1),
number_prefix: joi.string()
.min(1)
.max(16),
2020-05-04 15:48:07 +02:00
parameters: joi.array()
.min(1)
.items(
joi.object({
name: joi.string()
.max(128)
.required(),
range: joi.object({
values: joi.array()
.min(1),
min: joi.number(),
2020-05-14 15:36:47 +02:00
max: joi.number(),
type: joi.string()
.valid('array')
2020-05-04 15:48:07 +02:00
})
.oxor('values', 'min')
.oxor('values', 'max')
2020-05-14 15:36:47 +02:00
.oxor('type', 'values')
.oxor('type', 'min')
.oxor('type', 'max')
2020-05-04 15:48:07 +02:00
.required()
})
)
};
2020-05-14 12:31:57 +02:00
static input (data, param, template) { // validate data, param: new(everything required)/change(available attributes are validated)
2020-05-04 15:48:07 +02:00
if (param === 'new') {
2020-05-14 12:31:57 +02:00
if (template === 'treatment') {
return joi.object({
name: this.template.name.required(),
number_prefix: this.template.number_prefix.required(),
parameters: this.template.parameters.required()
}).validate(data);
}
else {
return joi.object({
name: this.template.name.required(),
parameters: this.template.parameters.required()
}).validate(data);
}
2020-05-04 15:48:07 +02:00
}
else if (param === 'change') {
2020-05-14 12:31:57 +02:00
if (template === 'treatment') {
return joi.object({
name: this.template.name,
number_prefix: this.template.number_prefix,
parameters: this.template.parameters
}).validate(data);
}
else {
return joi.object({
name: this.template.name,
parameters: this.template.parameters
}).validate(data);
}
2020-05-04 15:48:07 +02:00
}
else {
return{error: 'No parameter specified!', value: {}};
}
}
2020-05-14 12:31:57 +02:00
static output (data, template) { // validate output from database for needed properties, strip everything else
2020-05-06 14:39:04 +02:00
data = IdValidate.stringify(data);
2020-05-14 12:31:57 +02:00
let joiObject;
if (template === 'treatment') {
joiObject = {
_id: IdValidate.get(),
name: this.template.name,
version: this.template.version,
number_prefix: this.template.number_prefix,
parameters: this.template.parameters
};
}
else {
joiObject = {
_id: IdValidate.get(),
name: this.template.name,
version: this.template.version,
parameters: this.template.parameters
};
}
const {value, error} = joi.object(joiObject).validate(data, {stripUnknown: true});
2020-05-04 15:48:07 +02:00
return error !== undefined? null : value;
}
}