UNPKG

warrior-code-api

Version:
109 lines (87 loc) 2.64 kB
'use strict'; const Boom = require('boom'); const mongoose = require('mongoose'); const Campaign = mongoose.models.Campaign; /** * Get the list of campaigns for the current user. */ module.exports.index = (request, reply) => { let userId = request.auth.credentials._id; Campaign.find({players: userId, isActive: true}).then(reply); }; /** * Show an existing campaign. */ module.exports.show = (request, reply) => { let userId = request.auth.credentials._id; let campaignId = request.params.id; let filter = {_id: campaignId, 'players.user': userId, isActive: true}; Campaign.findOne(filter, (err, campaign) => { reply(campaign); }); }; /** * Create a new campaign. */ module.exports.create = (request, reply) => { let userId = request.auth.credentials._id; // Create the campaign instance. let campaign = new Campaign(request.payload); // Add the current user to the host and players list. campaign.host = userId; campaign.players = [userId]; // Save the campaign. campaign.save((err, campaign) => { if (err) { console.error(err); return reply(Boom.wrap(err, 400)); } // Respond with the successfully created campaign. reply(campaign); }); }; /** * Update an existing campaign. */ module.exports.update = (request, reply) => { // TODO }; /** * Add a player to the players list. * Only the same player or the host can add it. */ module.exports.addPlayer = (request, reply) => { const MAX_PLAYERS_MSG = 'This campaign has reach the max amount of players.'; const BAD_PLAYER_MSG = 'Only the same user or the host can add this player to the campaign.'; let userId = request.auth.credentials._id; let campaignId = request.params.id; let newPlayer = request.payload.player; // Get the campaign. Campaign.findById(campaignId, (err, campaign) => { if (err || !campaign) { return reply(Boom.notFound('The campaign does not exists.')); } // Check if the campaign is waiting for players. if (!campaign.isWaitingForPlayers) { return reply(Boom.badRequest(MAX_PLAYERS_MSG)); } // Check if the user is not the host or the new player. if (!(campaign.host.equals(userId) || newPlayer === userId)) { return reply(Boom.badRequest(BAD_PLAYER_MSG)); } // Add the new player let added = campaign.addPlayer(newPlayer); // Respond with a message that ensures if the player was added or not. reply({ player: newPlayer, added: added }); }); }; /** * Delete an existing campaign. * Administrators only. */ module.exports.delete = (request, reply) => { // TODO };