Created
June 8, 2015 08:59
-
-
Save i-van/8f09863ff8cfeeb79aa6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {{ gameId: string, userId: string }} data | |
* @param {Function} done | |
* @returns {*} | |
*/ | |
connectionMessage: function(data, done) { | |
var that = this; | |
async.waterfall([ | |
function(next) { | |
ApiUser.findOne({ _id: data.userId }, next); | |
}, | |
function(user, next) { | |
if (!user) { | |
return next(new ErrorMessage(ErrorMessage.USER_NOT_FOUND)); | |
} | |
that.id = user._id.toString(); | |
that.login = user.login; | |
ApiGame.findOne({ _id: data.gameId }, next); | |
}, | |
function(apiGame, next) { | |
try { | |
if (!apiGame) { | |
throw new ErrorMessage(ErrorMessage.GAME_NOT_FOUND); | |
} else if (apiGame.status === ApiGame.STATUS_STARTED) { | |
throw new ErrorMessage(ErrorMessage.GAME_IS_STARTED); | |
} else if (apiGame.status === ApiGame.STATUS_FINISHED) { | |
throw new ErrorMessage(ErrorMessage.GAME_IS_FINISHED); | |
} | |
var game = Game.findById(data.gameId) || new Game(data.gameId, apiGame.type); | |
if (game.isStarted) { | |
throw new ErrorMessage(ErrorMessage.GAME_IS_STARTED); | |
} else if (game.isFull()) { | |
throw new ErrorMessage(ErrorMessage.GAME_IS_FULL); | |
} | |
that.connectToGame(game); | |
// increment online | |
// change status to pending on first connection | |
var update = { $inc: { online: 1 } }; | |
if (apiGame.status === ApiGame.STATUS_CREATED) { | |
update.$set = { status: ApiGame.STATUS_PENDING }; | |
} | |
ApiGame.update({ _id: game.id }, update, next); | |
} catch (err) { | |
next(err); | |
} | |
}, | |
function(number, res, next) { | |
if (!config.features.autoStart || !that.game.isFull()) { | |
return next(); | |
} | |
async.parallel([ | |
that.game.start.bind(that.game), | |
ApiGame.update.bind(ApiGame, { _id: that.game.id }, { status: ApiGame.STATUS_STARTED }) | |
], next); | |
} | |
], function(err) { | |
try { | |
if (err instanceof ErrorMessage) { | |
that.send(err); | |
} else if (err) { | |
throw err; | |
} | |
done(); | |
} catch (e) { | |
done(e); | |
} | |
}); | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment