import Joi from '@hapi/joi'; import IdValidate from './id'; import UserValidate from './user'; import MaterialValidate from './material'; export default class SampleValidate { private static sample = { number: Joi.string() .max(128), color: Joi.string() .max(128), type: Joi.string() .max(128), batch: Joi.string() .max(128) .allow(''), condition: Joi.object(), notes: Joi.object({ comment: Joi.string() .max(512) .allow(''), sample_references: Joi.array() .items(Joi.object({ sample_id: IdValidate.get(), relation: Joi.string() .max(128) })), custom_fields: Joi.object() .pattern(/.*/, Joi.alternatives() .try( Joi.string().max(128), Joi.number(), Joi.boolean(), Joi.date() ) ) }) }; static input (data, param) { // validate input, set param to 'new' to make all attributes required if (param === 'new') { return Joi.object({ color: this.sample.color.required(), type: this.sample.type.required(), batch: this.sample.batch.required(), condition: this.sample.condition.required(), material_id: IdValidate.get().required(), notes: this.sample.notes.required() }).validate(data); } else if (param === 'change') { return Joi.object({ color: this.sample.color, type: this.sample.type, batch: this.sample.batch, condition: this.sample.condition, material_id: IdValidate.get(), notes: this.sample.notes, }).validate(data); } else if (param === 'new-admin') { return Joi.object({ number: this.sample.number, color: this.sample.color.required(), type: this.sample.type.required(), batch: this.sample.batch.required(), condition: this.sample.condition.required(), material_id: IdValidate.get().required(), notes: this.sample.notes.required() }).validate(data); } else { return{error: 'No parameter specified!', value: {}}; } } static output (data, param = 'refs') { // validate output and strip unwanted properties, returns null if not valid data = IdValidate.stringify(data); let joiObject; if (param === 'refs') { joiObject = { _id: IdValidate.get(), number: this.sample.number, color: this.sample.color, type: this.sample.type, batch: this.sample.batch, condition: this.sample.condition, material_id: IdValidate.get(), note_id: IdValidate.get().allow(null), user_id: IdValidate.get() }; } else if(param === 'details') { joiObject = { _id: IdValidate.get(), number: this.sample.number, color: this.sample.color, type: this.sample.type, batch: this.sample.batch, condition: this.sample.condition, material: MaterialValidate.outputV(), notes: this.sample.notes, user: UserValidate.username() } } else { return null; } const {value, error} = Joi.object(joiObject).validate(data, {stripUnknown: true}); return error !== undefined? null : value; } static query (data) { return Joi.object({ status: Joi.string().valid('validated', 'new', 'all') }).validate(data); } }