66 lines
2.0 KiB
JavaScript
66 lines
2.0 KiB
JavaScript
'use strict';
|
|
|
|
const Job = require('../model/job'),
|
|
Pilot = require('../model/pilot'),
|
|
ObjectId = require('mongodb').ObjectId,
|
|
userCtl = require('../controllers/user'),
|
|
{ updateUser_put } = require('./user'), // Import user controller functions
|
|
cache = require('../helpers/mem_cache'),
|
|
utils = require('../helpers/utils'),
|
|
{ Errors, UserTypes } = 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 id = req.params.id;
|
|
if (!ObjectId.isValid(id)) AppParamError.throw();
|
|
|
|
const pilot = await Pilot.findOne({ _id: ObjectId(id) }, null, { lean: true });
|
|
res.json(pilot);
|
|
}
|
|
|
|
// Update pilot (reuses user controller logic)
|
|
async function updatePilot_put(req, res) {
|
|
if (!req.body.kind) {
|
|
req.body.kind = UserTypes.PILOT;
|
|
}
|
|
// Reuse the user controller's updateUser_put function directly
|
|
return updateUser_put(req, res);
|
|
}
|
|
|
|
// Delete pilot (reuses user controller logic)
|
|
async function deletePilot(req, res) {
|
|
const id = req.params.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
|
|
} |