以下解决方案假定您从干净版本的排行榜示例开始。
第一步:声明一个新的集合来保存 IP 地址和日期信息。这可以添加到 Players 的定义下方。
IPs = new Meteor.Collection('ips');
第二步:将增量事件替换为调用我们的新方法givePoints。
Template.leaderboard.events({
'click input.inc': function() {
var playerId = Session.get('selected_player');
Meteor.call('givePoints', playerId, function(err) {
if (err)
alert(err.reason);
});
}
});
第三步:在服务端定义givePoints方法(this.connection只在服务端有效)。您可以通过在Meteor.isServer 检查内的任意位置插入以下内容或在/server 目录下创建一个新文件来执行此操作。
Meteor.methods({
givePoints: function(playerId) {
check(playerId, String);
// we want to use a date with a 1-day granularity
var startOfDay = new Date;
startOfDay.setHours(0, 0, 0, 0);
// the IP address of the caller
ip = this.connection.clientAddress;
// check by ip and date (these should be indexed)
if (IPs.findOne({ip: ip, date: startOfDay})) {
throw new Meteor.Error(403, 'You already voted!');
} else {
// the player has not voted yet
Players.update(playerId, {$inc: {score: 5}});
// make sure she cannot vote again today
IPs.insert({ip: ip, date: startOfDay});
}
}
});
完整代码见this gist。