问题描述
我正在关注排行榜的MeteorJS示例:
I'm following the MeteorJS example for a leaderboard here: https://www.meteor.com/examples/leaderboard
我想将投票限制为每天一次(每个IP地址)。最好的方法是什么?
I want to limit the votes to once per day (per IP address). What's the best way to do this?
推荐答案
以下解决方案假设您从排行榜示例的干净版本开始。
The following solution assumes you are starting with a clean version of the leaderboard example.
第一步:声明一个新的集合来保存IP地址和日期信息。这可以在玩家
的定义下面添加。
Step one: Declare a new collection to hold IP address and date information. This can be added just below the definition of Players
.
IPs = new Meteor.Collection('ips');
第二步:通过调用我们的新方法替换increment事件 givePoints
。
Step two: Replace the increment event with a call to our new method 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 $ c $下创建新文件来执行此操作c>目录。
Step three: Define the givePoints
method on the server (this.connection
only works on the server). 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.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});
}
}
});
完整的代码可以在。
这篇关于限制流星投注每天一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!