72 lines
1.8 KiB
JavaScript
72 lines
1.8 KiB
JavaScript
'use strict';
|
|
|
|
const Crop = require('../model/crop'),
|
|
Job = require('../model/job'),
|
|
Area = require('../model/area'),
|
|
ObjectId = require('mongodb').ObjectId,
|
|
{ Errors } = require('../helpers/constants'),
|
|
{ AppParamError, AppError } = require('../helpers/app_error');
|
|
|
|
async function getCrops_get(req, res) {
|
|
const crops = await Crop.find({});
|
|
res.json(crops);
|
|
}
|
|
|
|
async function createCrop_post(req, res) {
|
|
const _crop = req.body;
|
|
if (!_crop) AppParamError.throw();
|
|
|
|
delete _crop._id;
|
|
const crop = new Crop(_crop);
|
|
await crop.save();
|
|
res.json(crop);
|
|
}
|
|
|
|
async function getCrop_get(req, res) {
|
|
const crop = await Crop.findById(req.params.crop_id);
|
|
res.json(crop);
|
|
}
|
|
|
|
async function updateCrop_put(req, res) {
|
|
const _crop = req.body;
|
|
if (!_crop) AppParamError.throw();
|
|
|
|
delete _crop._id;
|
|
const crop = await Crop.findOneAndUpdate({ _id: req.params.crop_id }, _crop, { new: true, lean: true });
|
|
res.json(crop);
|
|
}
|
|
|
|
async function deleteCrop(req, res) {
|
|
const _pid = req.params.crop_id;
|
|
const cropId = ObjectId(_pid);
|
|
|
|
const checkRefs = [
|
|
Job.find({
|
|
$or: [
|
|
{ crop: cropId },
|
|
{ 'sprayAreas': { $elemMatch: { 'properties.crop': cropId } } }
|
|
]
|
|
}).limit(1),
|
|
Area.find({ 'properties.crop': cropId }).limit(1)
|
|
];
|
|
|
|
const data = await Promise.all(checkRefs);
|
|
if (data && data.filter(it => it.length).length) AppError.throw(Errors.HAS_REFERENCE);
|
|
const crop = await Crop.deleteOne({ _id: cropId });
|
|
res.json(crop);
|
|
}
|
|
|
|
async function search_post(req, res) {
|
|
const _options = {};
|
|
if (req.body.byUserId && ObjectId.isValid(req.body.byUserId))
|
|
_options.byPuid = ObjectId(req.body.byUserId);
|
|
else
|
|
AppParamError.throw();
|
|
|
|
const crops = await Crop.find(_options);
|
|
res.json(crops || []);
|
|
}
|
|
|
|
module.exports = {
|
|
getCrops_get, createCrop_post, getCrop_get, updateCrop_put, deleteCrop, search_post
|
|
} |