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
2020-07-14 12:07:43 +02:00

70 lines
1.8 KiB
TypeScript

import Joi from '@hapi/joi';
import IdValidate from './id';
// TODO: do not allow a . in the name
export default class TemplateValidate {
private static template = {
name: Joi.string()
.max(128),
version: Joi.number()
.min(1),
parameters: Joi.array()
.items(
Joi.object({
name: Joi.string()
.max(128)
.invalid('condition_template')
.required(),
range: Joi.object({
values: Joi.array()
.min(1),
min: Joi.number(),
max: Joi.number(),
type: Joi.string()
.valid('array')
})
.oxor('values', 'min')
.oxor('values', 'max')
.oxor('type', 'values')
.oxor('type', 'min')
.oxor('type', 'max')
.required()
})
)
};
static input (data, param) { // validate input, set param to 'new' to make all attributes required
if (param === 'new') {
return Joi.object({
name: this.template.name.required(),
parameters: this.template.parameters.required()
}).validate(data);
}
else if (param === 'change') {
return Joi.object({
name: this.template.name,
parameters: this.template.parameters
}).validate(data);
}
else {
return{error: 'No parameter specified!', value: {}};
}
}
static output (data) { // validate output and strip unwanted properties, returns null if not valid
data = IdValidate.stringify(data);
const {value, error} = Joi.object({
_id: IdValidate.get(),
name: this.template.name,
version: this.template.version,
parameters: this.template.parameters
}).validate(data, {stripUnknown: true});
return error !== undefined? null : value;
}
}