Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added match controller

  • Loading branch information...
commit d13bbb19ae5a6367c0e4f5f3c33def1ccd50387e 1 parent 2aa1576
Toan Tran authored
49 coffee/controllers/match.coffee
View
@@ -0,0 +1,49 @@
+
+exports.update = (req, res, next) ->
+ matchid = req.params.id
+ teamid = req.param 'teamid', ''
+ playerid = req.param 'playerid', ''
+ result = req.param 'result', ''
+ callback = (err) ->
+ res.send
+ success: false
+ error: err
+
+ if not matchid or not teamid or not playerid or not result
+ res.send
+ success: false
+ error: 'Ids empty'
+ else if result isnt 'win' and result isnt 'lose'
+ res.send
+ success: false
+ error: 'Invalid result'
+ else
+ matchsvc = require '../services/match'
+ utils = require '../services/utils'
+
+ utils.execute( matchsvc.addVote, matchid, playerid, teamid, result )
+ .then (err, args..., cb = ->) ->
+ return callback(err) if err
+
+ matchsvc.getById matchid, cb
+ .then (err, @am, cb = -> ) =>
+ return callback(err) if err
+ return callback('match not found') if not @am?
+
+ @totalplayers = @am?.teams?.map( (team) -> team?.members?.length ? 0 ).reduce( (prev, curr) ->
+ prev + curr
+ , 0 )
+ @totalvotes = @am?.votes?.length ? 0
+ @totalDecisions = matchsvc.countDecisions @am
+ if @totalvotes >= @totalplayers or @totalDecisions > @totalplayers / 2
+ matchsvc.finalize @am, cb
+ res.send
+ success: true
+ .then (err) =>
+ console.log err
+
+
+
+
+
+
32 coffee/services/match.coffee
View
@@ -130,12 +130,35 @@ exports.cancel = (am, callback = ->) ->
exports.addVote = (matchid, playerid, teamid, result, callback = ->) ->
+ console.assert matchid, 'matchid cannot be null or 0'
+ throw 'matchid cannot be null or 0' unless matchid
+ console.assert playerid, 'playerid cannot be null or 0'
+ throw 'playerid cannot be null or 0' unless matchid
+ console.assert teamid, 'teamid cannot be null or 0'
+ throw 'teamid cannot be null or 0' unless matchid
+ console.assert result is 'win' or result is 'lose', 'result must be win or lose'
+ throw 'result must be win or lose' unless result is 'win' or result is 'lose'
+
vote = {playerid, teamid, count: if result is 'win' then 1 else -1}
+ matchid = new matchRepo.ObjectId(matchid) if typeof matchid is 'string'
+ findObj =
+ _id: matchid
+ updateObj =
+ $addToSet:
+ votes: vote
+ $set:
+ updatedat: new Date()
+
+ try
+ matchRepo.update findObj, updateObj, {}, callback
+ catch e
+ console.trace e
+ throw e
-exports.countVotes = (am, callback = ->) ->
- callback 0 unless am?.votes?
+exports.countDecisions = (am) ->
+ return 0 unless am?.votes?
results = {}
# initialize the result object
@@ -152,6 +175,7 @@ exports.countVotes = (am, callback = ->) ->
results[teamid].count += count
Math.abs (results[String(am.teams[1]._id)].count - results[String(am.teams[0]._id)].count)
+
exports.finalize = (am, callback = -> ) ->
@@ -205,7 +229,7 @@ exports.finalize = (am, callback = -> ) ->
console.log "Team #{teamid} update stats with error #{err}" if err?
cb.apply @, arguments
- makeUpdatePlayerStats = () ->
+ makeUpdatePlayersStats = () ->
players = []
for team in am.teams
do (team) ->
@@ -242,7 +266,7 @@ exports.finalize = (am, callback = -> ) ->
console.log "Match #{am._id} Set team #{team._id} match complete with error #{err}" if err?
cb null
- utils.seriesAsync [makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayerStats(), makeSetTeamMatchComplete()], am, () ->
+ utils.seriesAsync [makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayersStats(), makeSetTeamMatchComplete()], am, () ->
console.log 'Done!'
240 controllers/match.js
View
@@ -1,190 +1,62 @@
-
-
-exports.update = function(req, res, next) {
- var matchid = req.params.id
- , teamid = req.param('teamid')
- , playerid = req.param('playerid')
- , result = req.param('result');
-
- if (!matchid || !teamid || !playerid || !result) {
- res.send({
- success: false
- , error: 'Ids empty'
- });
-
- return;
- }
-
- if (result !== 'win' && result !== 'lose') {
- res.send({
- success: false
- , error: 'Invalid result'
- });
-
- return;
- }
-
- vote({
- matchid: matchid
- , teamid: teamid
- , playerid: playerid
- , result: result
- }, function(error) {
- if (error) {
- res.send({
- success: false
- , error: error
- });
- } else {
- res.send({
- success: true
+(function() {
+ var __slice = Array.prototype.slice;
+
+ exports.update = function(req, res, next) {
+ var callback, matchid, matchsvc, playerid, result, teamid, utils,
+ _this = this;
+ matchid = req.params.id;
+ teamid = req.param('teamid', '');
+ playerid = req.param('playerid', '');
+ result = req.param('result', '');
+ callback = function(err) {
+ return res.send({
+ success: false,
+ error: err
});
- }
- });
-}
-
-
-function vote(inputs, callback) {
- callback = callback || function() {};
-
- if (!inputs) {
- callback('Inputs empty');
- return false;
- }
-
- var matchRepo = require('../repository/matches')
- , utils = require('utils')
- , voteObj = {
- playerid: inputs.playerid
- , teamid: inputs.teamid
- , count: inputs.result === 'win' ? 1 : -1
};
-
-
- matchRepo.addVote(inputs.matchid, voteObj, function( error, am) {
- if (error) {
- callback(error);
- return false;
- }
-
- // add this vote to player's profile
- addVoteToPlayer(inputs, function(error, player) {
- callback(error, player);
- return;
- });
-
- if (am && am.teams && (am.teams.length === 2) && am.votes) {
-
- var voteCount = am.votes.length
- , memberCount = 0
- , results = {};
-
- am.teams.forEach( function(team, index, teams) {
- memberCount += team.members ? team.members.length : 0;
-
- // initialize the result object for later
- results[String(team._id)] = {
- count: 0
- , opponentid: String(teams[(index + 1) % 2]._id)
- };
+ if (!matchid || !teamid || !playerid || !result) {
+ return res.send({
+ success: false,
+ error: 'Ids empty'
});
-
- if (voteCount >= memberCount) { // full votes
- // set match status complete
- matchRepo.setStatus(inputs.matchid, 'complete');
-
- // calculate result
- am.votes.forEach( function(item) {
- if (item && item.teamid) {
- results[item.teamid].count += item.count;
- }
- });
-
- // set stats for teams and players
- for(teamid in results) {
- var win = results[teamid].count >= 0;
-
- updateStats(teamid, results[teamid], win);
- }
-
- // move teams' match to complete match collection
- setTeamMatchComplete(am);
- }
- }
- });
-}
-
-
-function updateStats(teamid, data, win, callback) {
- var teamRepo = require('../repository/teams')
- , userRepo = require('../repository/users')
- , count = 2
- , fn = function(error, result) {
- count--;
-
- if (count <= 0) {
- callback();
- }
- };
-
- callback = callback || function() {};
-
- if (teamid) {
- teamRepo.updateStats(teamid, data.opponentid, win, fn);
- userRepo.updateStats(teamid, data.opponentid, win, fn);
- } else {
- callback();
- }
-
- return true;
-}
-
-
-function setTeamMatchComplete(am, callback) {
- var teamRepo = require('../repository/teams')
- , count = 0;
-
- callback = callback || function() {};
-
- if (am && am.teams && am.teams.length) {
- count = am.teams.length;
-
- am.teams.forEach( function(team) {
- teamRepo.completeMatch(String(team._id), am, function() {
- count--;
- if (count <= 0) {
- callback(arguments);
+ } else if (result !== 'win' && result !== 'lose') {
+ return res.send({
+ success: false,
+ error: 'Invalid result'
+ });
+ } else {
+ matchsvc = require('../services/match');
+ utils = require('../services/utils');
+ return utils.execute(matchsvc.addVote, matchid, playerid, teamid, result).then(function() {
+ var args, cb, err, _i;
+ err = arguments[0], args = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), cb = arguments[_i++];
+ if (cb == null) cb = function() {};
+ if (err) return callback(err);
+ return matchsvc.getById(matchid, cb);
+ }).then(function(err, am, cb) {
+ var _ref, _ref2, _ref3, _ref4, _ref5;
+ _this.am = am;
+ if (cb == null) cb = function() {};
+ if (err) return callback(err);
+ if (!(_this.am != null)) return callback('match not found');
+ _this.totalplayers = (_ref = _this.am) != null ? (_ref2 = _ref.teams) != null ? _ref2.map(function(team) {
+ var _ref3, _ref4;
+ return (_ref3 = team != null ? (_ref4 = team.members) != null ? _ref4.length : void 0 : void 0) != null ? _ref3 : 0;
+ }).reduce(function(prev, curr) {
+ return prev + curr;
+ }, 0) : void 0 : void 0;
+ _this.totalvotes = (_ref3 = (_ref4 = _this.am) != null ? (_ref5 = _ref4.votes) != null ? _ref5.length : void 0 : void 0) != null ? _ref3 : 0;
+ _this.totalDecisions = matchsvc.countDecisions(_this.am);
+ if (_this.totalvotes >= _this.totalplayers || _this.totalDecisions > _this.totalplayers / 2) {
+ matchsvc.finalize(_this.am, cb);
}
- });
- });
-
- } else {
- callback();
- }
-
- return true;
-}
-
-
-function addVoteToPlayer(inputs, callback) {
- var userRepo = require('../repository/users')
- , vote = {
- teamid: inputs.teamid
- , matchid: inputs.matchid
- , result: inputs.result
+ return res.send({
+ success: true
+ });
+ }).then(function(err) {
+ return console.log(err);
+ });
}
- , playerid= inputs.playerid;
-
- callback = callback || function() {};
-
- userRepo.addVote(playerid, vote, callback);
-
- return true;
-}
-
-
-
-
-
-
+ };
+}).call(this);
45 services/match.js
View
@@ -173,19 +173,46 @@
};
exports.addVote = function(matchid, playerid, teamid, result, callback) {
- var vote;
+ var findObj, updateObj, vote;
if (callback == null) callback = function() {};
- return vote = {
+ console.assert(matchid, 'matchid cannot be null or 0');
+ if (!matchid) throw 'matchid cannot be null or 0';
+ console.assert(playerid, 'playerid cannot be null or 0');
+ if (!matchid) throw 'playerid cannot be null or 0';
+ console.assert(teamid, 'teamid cannot be null or 0');
+ if (!matchid) throw 'teamid cannot be null or 0';
+ console.assert(result === 'win' || result === 'lose', 'result must be win or lose');
+ if (!(result === 'win' || result === 'lose')) {
+ throw 'result must be win or lose';
+ }
+ vote = {
playerid: playerid,
teamid: teamid,
count: result === 'win' ? 1 : -1
};
+ if (typeof matchid === 'string') matchid = new matchRepo.ObjectId(matchid);
+ findObj = {
+ _id: matchid
+ };
+ updateObj = {
+ $addToSet: {
+ votes: vote
+ },
+ $set: {
+ updatedat: new Date()
+ }
+ };
+ try {
+ return matchRepo.update(findObj, updateObj, {}, callback);
+ } catch (e) {
+ console.trace(e);
+ throw e;
+ }
};
- exports.countVotes = function(am, callback) {
+ exports.countDecisions = function(am) {
var count, results, teamid, _i, _len, _ref, _ref2;
- if (callback == null) callback = function() {};
- if ((am != null ? am.votes : void 0) == null) callback(0);
+ if ((am != null ? am.votes : void 0) == null) return 0;
results = {};
results[String(am.teams[0]._id)] = {
count: 0,
@@ -206,7 +233,7 @@
};
exports.finalize = function(am, callback) {
- var count, makeSetMatchComplete, makeSetTeamMatchComplete, makeUpdatePlayerStats, makeUpdateTeamStats, maxCount, playerSvc, result, results, teamSvc, teamid, utils, _fn, _i, _len, _ref, _ref2, _ref3;
+ var count, makeSetMatchComplete, makeSetTeamMatchComplete, makeUpdatePlayersStats, makeUpdateTeamStats, maxCount, playerSvc, result, results, teamSvc, teamid, utils, _fn, _i, _len, _ref, _ref2, _ref3;
if (callback == null) callback = function() {};
teamSvc = require('./team');
playerSvc = require('./user');
@@ -274,8 +301,8 @@
return _results;
};
};
- makeUpdatePlayerStats = function() {
- var players, team, _fn2, _j, _len2, _ref4;
+ makeUpdatePlayersStats = function() {
+ var makeUpdatePlayerStats, players, team, _fn2, _j, _len2, _ref4;
players = [];
_ref4 = am.teams;
_fn2 = function(team) {
@@ -339,7 +366,7 @@
return cb(null);
};
};
- return utils.seriesAsync([makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayerStats(), makeSetTeamMatchComplete()], am, function() {
+ return utils.seriesAsync([makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayersStats(), makeSetTeamMatchComplete()], am, function() {
return console.log('Done!');
});
};
Please sign in to comment.
Something went wrong with that request. Please try again.