import Joi from '@hapi/joi'; import IdValidate from './id'; export default class TemplateValidate { private static template = { name: Joi.string() .max(128), version: Joi.number() .min(1), number_prefix: Joi.string() .pattern(/^[a-zA-Z]+$/) .min(1) .max(16), 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(), 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, template) { // validate data, param: new(everything required)/change(available attributes are validated) if (param === 'new') { 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); } } else if (param === 'change') { 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); } } else { return{error: 'No parameter specified!', value: {}}; } } static output (data, template) { // validate output from database for needed properties, strip everything else data = IdValidate.stringify(data); 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}); return error !== undefined? null : value; } }