【问题标题】:Limit Meteor Vote Once Per Day每天一次限制流星投票
【发布时间】:2014-09-09 01:54:20
【问题描述】:

我在这里关注 MeteorJS 的排行榜示例:https://www.meteor.com/examples/leaderboard

我想将投票限制为每天一次(每个 IP 地址)。最好的方法是什么?

【问题讨论】:

  • 为 upvotes 创建一个 Meteor 方法。在 Method 中可以通过 this.connection.clientAddresshttp://docs.meteor.com/#method_connection 访问投票者的 ip
  • @imslavko 你能给我一些源代码吗?谢谢。

标签: javascript meteor ip leaderboard vote


【解决方案1】:

以下解决方案假定您从干净版本的排行榜示例开始。

第一步:声明一个新的集合来保存 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

【讨论】:

  • 一切看起来都不错,但由于某种原因它无法正常工作。我应该将第三步放在Meteor.isServer 函数中吗?我没有错误。我尝试在该功能之前,之中和之后放入。你有什么建议吗?
  • 是的,你想把它放在Meteor.isServer 检查下,或者把它放在/server 目录中任意位置的新文件中。我修改了答案以更清楚。如果这仍然不适合您,我可以创建一个要点。
  • 您介意创建一个要点吗?不明白为什么它不起作用。非常感谢。
  • 好的,我在答案末尾添加了要点。因此,如果您查看一个干净的排行榜项目并将leaderboard.js 替换为上述内容,它应该可以工作。在本地运行时,预期的体验是您可以投票给一个人,然后直到第二天才能再次投票(除了第二次投票不会改变分数之外,没有任何视觉反馈)。
  • 当然——我用一个例子更新了代码。如果该方法从服务器收到错误,它将提醒用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多