Hello guys,
I have the following autorun at onCreated, see the second autorun,
I want to set player2 as Meteor.userId() on page load if player2 is null and different to player1.
Template.Page_game.onCreated(function() {
this.getGameId = () => FlowRouter.getParam('id');
this.autorun(() => {
this.subscribe('games.getById', this.getGameId());
});
this.getGame = () => {
let id = FlowRouter.getParam('id');
return Games.findOne(id);
};
this.autorun(() => {
let game = this.getGame();
if (!game) {
return;
}
if (!['onHold', 'inProgress'].includes(game.status)) {
FlowRouter.go('home');
}
if (!game.player2 && game.player1 != Meteor.userId()) {
setPlayer2.call({
gameId: game._id
},
(err, result) => {
if (err) {
console.log('err');
console.log(err);
}
}
);
}
});
});
I have the following method to kick out player2, (set game.player2 = null)
export const kickPlayer2 = new ValidatedMethod({
name: 'games.kickPlayer2',
validate: new SimpleSchema({
gameId: { type: String, optional: true, regEx: SimpleSchema.RegEx.Id },
}).validator({ clean: true, filter: false }),
run({ gameId }) {
if (!this.userId) {
throw new Meteor.Error('games.kickPlayer2.notLoggedIn',
'Must be logged in to kick player2.');
}
if (!this.isSimulation) {
let game = Games.findOne(gameId);
if (game.status != 'onHold') {
throw new Meteor.Error('games.kickPlayer2.accessDenied',
'Cannot kick player2 because game status is not onHold.');
}
if (!game.player2) {
throw new Meteor.Error('games.kickPlayer2.accessDenied',
'Cannot kick player2 because it is already null.');
}
if (game.player1 != this.userId) {
throw new Meteor.Error('games.kickPlayer2.accessDenied',
'Cannot kick player2 current user is not player1.');
}
return Games.update(game._id, {
$set: {
player2: null
}
});
}
}
});
LOL, my issue is that as soon as player2 is kick out, the autorun adds him back.
How can I avoid this?
Thanks,