warrior-code-api
Version:
API for Warrior-Code.
70 lines (51 loc) • 1.96 kB
JavaScript
;
const mongoose = require('mongoose');
const CAMPAIGN_DEFAULT_MAX_PLAYERS = 3;
/**
* Generate a random campaign name.
* @return {String} name
*/
const generateCampaignRandomName = () => {
return 'Holla';
};
const CampaignSchema = new mongoose.Schema({
// Campaign name.
name: { type: String, required: true, default: generateCampaignRandomName },
// Associate a world (collection of maps).
world: { type: String, required: true },
// Associate up to three players.
players: [{ type: mongoose.Schema.ObjectId, ref: 'User' }],
maxPlayers: { type: Number, default: CAMPAIGN_DEFAULT_MAX_PLAYERS },
// User that acts as host have the ability to kick players.
host: { type: mongoose.Schema.ObjectId, ref: 'User' },
// Show in the lobby if it is waiting for players.
isWaitingForPlayers: { type: Boolean, default: true },
// Set the status.
isActive: { type: Boolean, default: true }
});
CampaignSchema.path('players').validate(function () {
return (this.players.length < this.maxPlayers);
});
/**
* Add a player to the players list if this does not exist there yet.
* Will not save the campaign.
* @param {ObjectId} player
* @return {Boolean} addded
*/
CampaignSchema.methods.addPlayer = function(player) {
// Get the current amount of players.
let currentAmountOfPlayer = this.players.length;
// Convert the players array to set in order to avoid duplicates and add it.
let players = new Set(this.players);
players = players.add(player);
// Check if the has reach the max amount of players.
if (currentAmountOfPlayer === this.maxPlayers) {
this.isWaitingForPlayers = false;
}
// Convert to array again.
this.players = players.values();
// Return if a new player is in the list.
return currentAmountOfPlayer > this.players.length;
};
CampaignSchema.statics.generateRandomName = generateCampaignRandomName;
module.exports = mongoose.model('Campaign', CampaignSchema);