我在这里遵循 MeteorJS 的排行榜示例:https://www.meteor.com/examples/leaderboard
我想将投票限制为每天一次(每个 IP 地址)。最好的方法是什么?
最佳答案
以下解决方案假设您从排行榜示例的干净版本开始。
第一步:声明一个新集合来保存 IP 地址和日期信息。可以将其添加到 Players
定义的正下方。
IPs = new Meteor.Collection('ips');
第二步:用对我们的新方法givePoints
的调用替换increment事件。
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 .
关于javascript - 每天限制 meteor 投票一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24816324/