opt-cc/api/routes/players.js

57 lines
1.6 KiB
JavaScript

"use strict";
// modules
const express = require('express');
const logger = require('debug')('cc:wars');
// HTTP status codes by name
const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling');
// Mongoose Model using mongoDB
const CampaignModel = require('../models/campaign');
const PlayerModel = require('../models/player');
const WarModel = require('../models/war');
const campaignPlayer = express.Router();
// routes **********************
campaignPlayer.route('/:campaignId/:playerName')
.get((req, res, next) => {
CampaignModel.findById(req.params.campaignId, (err, campaign) => {
if (err) return next(err);
WarModel.find({campaign: req.params.campaignId}, '_id', (err, wars) => {
if (err) return next(err);
const warIds = wars.map((obj) => {
return obj._id;
});
PlayerModel.find({name: req.params.playerName, warId: {"$in": warIds}})
.populate('warId')
.exec((err, items) => {
if (err) return next(err);
if (!items || items.length === 0) {
const err = new Error('unknown player name');
err.status = codes.notfound;
return next(err)
}
res.locals.items = {
name: req.params.playerName,
campaign: campaign,
players: items
};
next();
})
})
})
})
.all(
routerHandling.httpMethodNotAllowed
);
campaignPlayer.use(routerHandling.emptyResponse);
module.exports = campaignPlayer;