opt-cc/api/routes/overview.js

111 lines
3.3 KiB
JavaScript
Raw Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
2017-05-10 11:04:06 +02:00
// 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();
2017-05-10 11:04:06 +02:00
// routes **********************
overview.route('/')
2018-02-26 09:04:27 +01:00
.get((req, res, next) => {
let countOpfor = 0;
let countBlufor = 0;
const armyOverview = {
BLUFOR: {
2018-03-12 09:26:44 +01:00
squads: [],
2018-02-26 09:04:27 +01:00
},
OPFOR: {
2018-03-12 09:26:44 +01:00
squads: [],
},
2018-02-26 09:04:27 +01:00
};
2017-05-10 11:04:06 +02:00
2018-02-26 09:04:27 +01:00
SquadModel.find({}, {'sortingNumber': 0, 'updatedAt': 0, 'timestamp': 0, '__v': 0}, {
sort: {
sortingNumber: 'asc',
2018-03-12 09:26:44 +01:00
name: 'asc',
},
2018-02-26 09:04:27 +01:00
}, (err, squads) => {
2017-05-10 11:04:06 +02:00
if (err) {
return next(err);
}
2018-02-26 09:04:27 +01:00
async.eachSeries(squads, (squad, callback) => {
UserModel.find({squadId: squad._id}, {
'squadId': 0,
'updatedAt': 0,
'timestamp': 0,
2018-03-12 09:26:44 +01:00
'__v': 0,
2018-02-26 09:04:27 +01:00
}, {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;
2018-03-12 09:26:44 +01:00
squadMembers.push(usr);
2018-02-26 09:04:27 +01:00
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;
if (s.fraction === 'BLUFOR') {
delete s.fraction;
armyOverview.BLUFOR.squads.push(s);
countBlufor += s.members.length;
}
if (s.fraction === 'OPFOR') {
delete s.fraction;
armyOverview.OPFOR.squads.push(s);
countOpfor += s.members.length;
}
}
callback();
});
});
}, (err) => {
if (err) {
return next(err);
}
2018-02-26 09:04:27 +01:00
armyOverview.BLUFOR.memberCount = countBlufor;
armyOverview.OPFOR.memberCount = countOpfor;
res.locals.items = armyOverview;
res.locals.processed = true;
next();
});
2017-05-10 11:04:06 +02:00
});
2018-02-26 09:04:27 +01:00
})
.all(
routerHandling.httpMethodNotAllowed
);
2017-05-10 11:04:06 +02:00
overview.use(routerHandling.emptyResponse);
module.exports = overview;