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/sample.ts
2020-05-18 09:58:15 +02:00

82 lines
2.0 KiB
TypeScript

import Joi from '@hapi/joi';
import IdValidate from './id';
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(''),
notes: Joi.object({
comment: Joi.string()
.max(512),
sample_references: Joi.array()
.items(Joi.object({
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 data, param: new(everything required)/change(available attributes are validated)
if (param === 'new') {
return Joi.object({
color: this.sample.color.required(),
type: this.sample.type.required(),
batch: this.sample.batch.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,
material_id: IdValidate.get(),
notes: this.sample.notes,
}).validate(data);
}
else {
return{error: 'No parameter specified!', value: {}};
}
}
static output (data) {
data = IdValidate.stringify(data);
const {value, error} = Joi.object({
_id: IdValidate.get(),
number: this.sample.number,
color: this.sample.color,
type: this.sample.type,
batch: this.sample.batch,
material_id: IdValidate.get(),
note_id: IdValidate.get().allow(null),
user_id: IdValidate.get()
}).validate(data, {stripUnknown: true});
return error !== undefined? null : value;
}
}