'use strict'; const Job = require('../model/job'), Pilot = require('../model/pilot'), ObjectId = require('mongodb').ObjectId, userCtl = require('../controllers/user'), cache = require('../helpers/mem_cache'), utils = require('../helpers/utils'), { Errors } = require('../helpers/constants'), { AppParamError, AppError } = require('../helpers/app_error'); async function createPilot_post(req, res) { // Save/Create a pilot const _pilot = req.body; delete _pilot._id; await userCtl.ensureParentExists(_pilot); const newPilot = new Pilot(_pilot); const pilot = await newPilot.save(); res.json(pilot); } async function getPilot_get(req, res) { const cId = req.params.pilot_id; if (!ObjectId.isValid(cId)) AppParamError.throw(); const pilot = await Pilot.findOne({ _id: ObjectId(cId) }, null, { lean: true }); res.json(pilot); } async function updatePilot_put(req, res) { const _pilot = req.body; if (!_pilot || !utils.isObjectId(_pilot._id)) AppParamError.throw(); if (utils.isBlank(_pilot.username) && !utils.isBlank(_pilot.password)) _pilot.password = undefined; if (!_pilot.hasOwnProperty('active')) _pilot.active = true; const pilot = await Pilot.findOneAndUpdate({ _id: ObjectId(_pilot._id) }, _pilot, { runValidators: true, new: true, lean: true }); res.json(pilot); } async function deletePilot(req, res) { const _id = req.params.pilot_id; if (!utils.isObjectId(_id)) AppParamError.throw(); const nOfJobs = await Job.countDocuments({ 'operator': ObjectId(_id) }); if (nOfJobs) AppError.throw(Errors.HAS_REFERENCE); const pilot = await Pilot.findById(ObjectId(_id)); if (pilot) await pilot.removeFull(); cache.delete(_id); res.json({ ok: true }); } async function search_post(req, res) { if (!req.body || !utils.isObjectId(req.body.byUserId)) AppParamError.throw(); const pilots = await Pilot.find({ parent: ObjectId(req.body.byUserId), markedDelete: { $ne: true } }, "-password", { lean: true }); res.json(pilots); } module.exports = { createPilot_post, getPilot_get, updatePilot_put, deletePilot, search_post }