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

73 lines
2.0 KiB
TypeScript
Raw Normal View History

import Joi from '@hapi/joi';
2020-05-04 15:48:07 +02:00
import IdValidate from './id';
2020-07-14 12:07:43 +02:00
// TODO: do not allow a . in the name
2020-05-04 15:48:07 +02:00
export default class TemplateValidate {
private static template = {
name: Joi.string()
2020-05-04 15:48:07 +02:00
.max(128),
version: Joi.number()
2020-05-14 12:31:57 +02:00
.min(1),
parameters: Joi.array()
2020-05-04 15:48:07 +02:00
.items(
Joi.object({
name: Joi.string()
2020-05-04 15:48:07 +02:00
.max(128)
2020-07-15 13:11:33 +02:00
.invalid('condition_template', 'material_template')
.pattern(/^[^.]+$/)
.required()
.messages({'string.pattern.base': 'name must not contain a dot'}),
2020-05-04 15:48:07 +02:00
range: Joi.object({
values: Joi.array()
2020-05-04 15:48:07 +02:00
.min(1),
min: Joi.number(),
2020-05-04 15:48:07 +02:00
max: Joi.number(),
2020-05-14 15:36:47 +02:00
type: Joi.string()
2020-05-14 15:36:47 +02:00
.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()
})
)
};
static input (data, param) { // validate input, set param to 'new' to make all attributes required
2020-05-04 15:48:07 +02:00
if (param === 'new') {
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') {
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: {}};
}
}
static output (data) { // validate output and strip unwanted properties, returns null if not valid
2020-05-06 14:39:04 +02:00
data = IdValidate.stringify(data);
const {value, error} = Joi.object({
_id: IdValidate.get(),
name: this.template.name,
version: this.template.version,
2020-07-23 15:25:45 +02:00
first_id: IdValidate.get(),
parameters: this.template.parameters
}).validate(data, {stripUnknown: true});
2020-05-04 15:48:07 +02:00
return error !== undefined? null : value;
}
}