opt-cc/api/routes/overview.js

105 lines
2.7 KiB
JavaScript
Raw Normal View History

2017-05-10 11:04:06 +02:00
"use strict";
// modules
const async = require('async');
const express = require('express');
const logger = require('debug')('cc:overview');
// HTTP status codes by name
const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling');
// Mongoose Model using mongoDB
const UserModel = require('../models/user');
const SquadModel = require('../models/squad');
const RankModel = require('../models/rank');
const overview = express.Router();
// routes **********************
overview.route('/')
.get((req, res, next) => {
let countOpfor = 0;
let countBlufor = 0;
const armyOverview = {
NATO: {
squads: []
},
CSAT: {
squads: []
}
};
SquadModel.find({}, {'sortingNumber': 0, 'updatedAt': 0, 'timestamp': 0, '__v': 0}, {
sort: {
sortingNumber: 'asc',
name: 'asc'
}
}, (err, squads) => {
if (err) {
return next(err);
}
async.eachSeries(squads, (squad, callback) => {
UserModel.find({squadId: squad._id}, {
'squadId': 0,
'updatedAt': 0,
'timestamp': 0,
'__v': 0
}, {sort: {rankLvl: 'desc', name: 'asc'}}, (err, users) => {
const squadMembers = [];
async.eachSeries(users, (user, callback) => {
RankModel.findOne({level: user.rankLvl, fraction: squad.fraction}, (err, rank) => {
if (err) {
return next(err);
}
const usr = user.toObject();
usr.rank = rank.name;
delete usr.rankLvl;
squadMembers.push(usr)
callback();
});
}, (err) => {
if (err) {
return next(err);
}
const s = squad.toObject();
s.members = squadMembers;
s.memberCount = squadMembers.length;
if (s.fraction === 'BLUFOR') {
delete s.fraction;
armyOverview.NATO.squads.push(s);
countBlufor += s.members.length;
}
if (s.fraction === 'OPFOR') {
delete s.fraction;
armyOverview.CSAT.squads.push(s);
countOpfor += s.members.length;
}
callback();
});
});
}, (err) => {
if (err) {
return next(err);
}
armyOverview.NATO.memberCount = countBlufor;
armyOverview.CSAT.memberCount = countOpfor;
res.locals.items = armyOverview;
res.locals.processed = true;
next();
});
});
})
.all(
routerHandling.httpMethodNotAllowed
);
overview.use(routerHandling.emptyResponse);
module.exports = overview;