109 lines
3.3 KiB
JavaScript
109 lines
3.3 KiB
JavaScript
'use strict';
|
|
|
|
// modules
|
|
const async = require('async');
|
|
const express = require('express');
|
|
|
|
// HTTP status codes by name
|
|
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 = new express.Router();
|
|
|
|
// routes **********************
|
|
overview.route('/')
|
|
.get((req, res, next) => {
|
|
const fractions = ['BLUFOR', 'OPFOR'];
|
|
const fractionMemberCount = [0, 0];
|
|
const armyOverview = [
|
|
{squads: []},
|
|
{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) => {
|
|
const usr = user.toObject();
|
|
RankModel.findOne({level: user.rankLvl, fraction: squad.fraction}, (err, rank) => {
|
|
if (err) {
|
|
return next(err);
|
|
}
|
|
|
|
// not defined if rank was deleted / rankLvl not available for fraction
|
|
if (rank) {
|
|
usr.rank = rank.name;
|
|
}
|
|
delete usr.rankLvl;
|
|
squadMembers.push(usr);
|
|
|
|
callback();
|
|
});
|
|
}, (err) => {
|
|
if (err) {
|
|
return next(err);
|
|
}
|
|
|
|
// do not return empty squads
|
|
if (squadMembers.length > 0) {
|
|
const s = squad.toObject();
|
|
s.members = squadMembers;
|
|
s.memberCount = squadMembers.length;
|
|
|
|
for (let i = 0; i < fractions.length; i++) {
|
|
if (s.fraction === fractions[i]) {
|
|
delete s.fraction;
|
|
armyOverview[i].squads.push(s);
|
|
fractionMemberCount[i] += s.members.length;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
callback();
|
|
});
|
|
});
|
|
}, (err) => {
|
|
if (err) {
|
|
return next(err);
|
|
}
|
|
|
|
for (let i = 0; i < fractions.length; i++) {
|
|
armyOverview[i].memberCount = fractionMemberCount[i];
|
|
}
|
|
|
|
res.locals.items = armyOverview;
|
|
res.locals.processed = true;
|
|
next();
|
|
});
|
|
});
|
|
})
|
|
|
|
.all(
|
|
routerHandling.httpMethodNotAllowed
|
|
);
|
|
|
|
|
|
overview.use(routerHandling.emptyResponse);
|
|
|
|
|
|
module.exports = overview;
|