opt-cc/api/routes/campaigns.js

82 lines
2.7 KiB
JavaScript

'use strict';
// modules
const express = require('express');
// HTTP status codes by name
const codes = require('./http-codes');
const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
const checkMT = require('../middleware/permission-check').checkMT;
const routerHandling = require('../middleware/router-handling');
const idValidator = require('../middleware/validators').idValidator;
// Mongoose Model using mongoDB
const CampaignModel = require('../models/campaign');
const WarModel = require('../models/war');
// util
const genericGetById = require('./_generic').genericGetById;
const genericPatch = require('./_generic').genericPatch;
const campaigns = new express.Router();
// routes **********************
campaigns.route('/')
.post(apiAuthenticationMiddleware, checkMT, (req, res, next) => {
const campaign = new CampaignModel(req.body);
// timestamp and default are set automatically by Mongoose Schema Validation
campaign.save((err) => {
if (err) {
err.status = codes.wrongrequest;
err.message += ' in fields: ' + Object.getOwnPropertyNames(err.errors);
return next(err);
}
res.status(codes.created);
res.locals.items = campaign;
next();
});
})
.all(
routerHandling.httpMethodNotAllowed
);
campaigns.route('/:id')
.get(idValidator, (req, res, next) => {
return genericGetById(req, res, next, CampaignModel);
})
.patch(apiAuthenticationMiddleware, checkMT, (req, res, next) => {
return genericPatch(req, res, next, CampaignModel);
})
.delete((req, res, next) => {
CampaignModel.findByIdAndRemove(req.params.id, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
return next(err);
} else if (!item) {
err = new Error('item not found');
err.status = codes.notfound;
return next(err);
}
WarModel.find({campaign: req.params.id}).remove().exec();
// TODO: remove all the war logs from fs here!!!
// TODO: remove all LOG entries from DB!!!
res.locals.processed = true;
next();
});
})
.all(
routerHandling.httpMethodNotAllowed
);
// this middleware function can be used, if you like or remove it
// it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
campaigns.use(routerHandling.emptyResponse);
module.exports = campaigns;