[英]Limit Meteor Vote Once Per Day
I'm following the MeteorJS example for a leaderboard here: https://www.meteor.com/examples/leaderboard 我在这里遵循排行榜的MeteorJS示例: https ://www.meteor.com/examples/leaderboard
I want to limit the votes to once per day (per IP address). 我想将投票限制为每天一次(每个IP地址)。 What's the best way to do this? 最好的方法是什么?
The following solution assumes you are starting with a clean version of the leaderboard example. 以下解决方案假定您从排行榜示例的全新版本开始。
Step one: Declare a new collection to hold IP address and date information. 第一步:声明一个新集合以保存IP地址和日期信息。 This can be added just below the definition of Players
. 可以在Players
的定义下方添加。
IPs = new Meteor.Collection('ips');
Step two: Replace the increment event with a call to our new method givePoints
. 第二步:用对我们的新方法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);
});
}
});
Step three: Define the givePoints
method on the server ( this.connection
only works on the server). 第三步:在服务器上定义givePoints
方法( this.connection
仅在服务器上有效)。 You can do this by inserting the following anywhere inside of the Meteor.isServer
check or by creating a new file under the /server
directory. 您可以通过在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});
}
}
});
The complete code can be seen in this gist . 完整的代码可以在本要点中看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.