[英]Limit Meteor Vote Once Per Day
我在這里遵循排行榜的MeteorJS示例: https ://www.meteor.com/examples/leaderboard
我想將投票限制為每天一次(每個IP地址)。 最好的方法是什么?
以下解決方案假定您從排行榜示例的全新版本開始。
第一步:聲明一個新集合以保存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});
}
}
});
完整的代碼可以在本要點中看到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.