65 lines
2.5 KiB
TypeScript
65 lines
2.5 KiB
TypeScript
![]() |
import express from 'express';
|
||
|
import mongoose from 'mongoose';
|
||
|
|
||
|
import ConditionValidate from './validate/condition';
|
||
|
import ParametersValidate from './validate/parameters';
|
||
|
import res400 from './validate/res400';
|
||
|
import SampleModel from '../models/sample';
|
||
|
import ConditionModel from '../models/condition';
|
||
|
import TreatmentTemplateModel from '../models/treatment_template';
|
||
|
|
||
|
|
||
|
const router = express.Router();
|
||
|
|
||
|
router.post('/condition/new', async (req, res, next) => {
|
||
|
if (!req.auth(res, ['write', 'maintain', 'dev', 'admin'], 'basic')) return;
|
||
|
|
||
|
const {error, value: condition} = ConditionValidate.input(req.body, 'new');
|
||
|
if (error) return res400(error, res);
|
||
|
|
||
|
if (!await sampleIdCheck(condition, req, res, next)) return;
|
||
|
if (!await numberCheck(condition, res, next)) return;
|
||
|
if (!await treatmentCheck(condition, res, next)) return;
|
||
|
|
||
|
new ConditionModel(condition).save((err, data) => {
|
||
|
if (err) return next(err);
|
||
|
res.json(ConditionValidate.output(data.toObject()));
|
||
|
});
|
||
|
})
|
||
|
|
||
|
|
||
|
module.exports = router;
|
||
|
|
||
|
|
||
|
async function sampleIdCheck (condition, req, res, next) { // validate sample_id, returns false if invalid
|
||
|
const sampleData = await SampleModel.findById(condition.sample_id).lean().exec().catch(err => {next(err); return false;}) as any;
|
||
|
if (!sampleData) { // sample_id not found
|
||
|
res.status(400).json({status: 'Sample id not available'});
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
if (sampleData.user_id.toString() !== req.authDetails.id && !req.auth(res, ['maintain', 'admin'], 'basic')) return false; // sample does not belong to user
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
async function numberCheck (condition, res, next) { // validate number, returns false if invalid
|
||
|
const data = await ConditionModel.find({sample_id: new mongoose.Types.ObjectId(condition.sample_id), number: condition.number}).lean().exec().catch(err => {next(err); return false;}) as any;
|
||
|
if (data.length) {
|
||
|
res.status(400).json({status: 'Condition number already taken'});
|
||
|
return false;
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
async function treatmentCheck (condition, res, next) {
|
||
|
const treatmentData = await TreatmentTemplateModel.findById(condition.treatment_template).lean().exec().catch(err => {next(err); return false;}) as any;
|
||
|
if (!treatmentData) { // sample_id not found
|
||
|
res.status(400).json({status: 'Treatment template not available'});
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
// validate parameters
|
||
|
const {error, value: ignore} = ParametersValidate.input(condition.parameters, treatmentData.parameters);
|
||
|
if (error) {res400(error, res); return false;}
|
||
|
return true;
|
||
|
}
|