Skip to content

Instantly share code, notes, and snippets.

@i-van
Created June 8, 2015 08:58
Show Gist options
  • Save i-van/385d09351bad0ae0db83 to your computer and use it in GitHub Desktop.
Save i-van/385d09351bad0ae0db83 to your computer and use it in GitHub Desktop.
/**
* @param {{ gameId: string, userId: string }} data
* @param {Function} done
* @returns {*}
*/
connectionMessage: async.cps(function(data) {
var user = await(ApiUser.findOne.bind(ApiUser, { _id: data.userId })),
apiGame = await(ApiGame.findOne.bind(ApiGame, { _id: data.gameId }));
try {
if (!user) {
throw new ErrorMessage(ErrorMessage.USER_NOT_FOUND);
} else 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);
}
this.id = user._id.toString();
this.login = user.login;
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);
}
this.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 };
}
await(ApiGame.update.bind(ApiGame, { _id: game.id }, update));
if (config.features.autoStart && this.game.isFull()) {
await(this.game.start.bind(this.game));
await(ApiGame.update.bind(ApiGame, { _id: this.game.id }, { status: ApiGame.STATUS_STARTED }));
}
} catch (err) {
if (err instanceof ErrorMessage) {
this.send(err);
} else {
throw err;
}
}
}),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment