opt-cc/opt-cc-api/routes/awardings.js

104 lines
3.1 KiB
JavaScript

"use strict";
// modules
const express = require('express');
const logger = require('debug')('cc:awardings');
// HTTP status codes by name
const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling');
// Mongoose Model using mongoDB
const AwardingModel = require('../models/awarding');
const awarding = express.Router();
// routes **********************
awarding.route('/')
.get((req, res, next) => {
const filter = {};
if (req.query.userId) {
filter.userId = req.query.userId;
}
if (req.query.simple) {
AwardingModel.find(filter, {}, {sort: {date: 'desc'}}, (err, items) => {
if (err) {
err.status = codes.servererror;
return next(err);
// with return before (or after) the next(err) we prevent that the code continues here after next(err) has finished.
// this saves an extra else {..}
}
// if the collection is empty we do not send empty arrays back.
if (items && items.length > 0) {
res.locals.items = items;
}
res.locals.processed = true;
next();
});
} else {
AwardingModel.find(filter, {}, {sort: {date: 'desc'}})
.populate('decorationId').exec((err, items) => {
if (err) {
err.status = codes.servererror;
return next(err);
// with return before (or after) the next(err) we prevent that the code continues here after next(err) has finished.
// this saves an extra else {..}
}
// if the collection is empty we do not send empty arrays back.
if (items && items.length > 0) {
res.locals.items = items;
}
res.locals.processed = true;
next();
});
}
})
.post((req, res, next) => {
const rank = new AwardingModel(req.body);
// timestamp and default are set automatically by Mongoose Schema Validation
rank.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 = rank;
next();
});
})
.all(
routerHandling.httpMethodNotAllowed
);
awarding.route('/:id')
.delete((req, res, next) => {
AwardingModel.findByIdAndRemove(req.params.id, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("item not found");
err.status = codes.notfound;
}
// we don't set res.locals.items and thus it will send a 204 (no content) at the end. see last handler user.use(..)
res.locals.processed = true;
next(err); // this works because err is in normal case undefined and that is the same as no parameter
});
})
.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
awarding.use(routerHandling.emptyResponse);
module.exports = awarding;