这是一个我已经粗略完成但尚未提交给 Atmosphere 的包(等到我熟悉 tinytest 并为其编写单元测试)。
https://github.com/zeroasterisk/Meteor-Throttle
随意使用、扩展、修复和贡献(鼓励请求请求)
这个概念很简单,它只在服务器上运行(应该只运行)。
你首先需要为你想要限制的东西想出一个唯一的键......
例如:Meteor.userId() + 'my-function-name' + 'whatever'
此系统使用新的 Collection 'throttle' 和一些辅助方法来:
check、set 和 purge 记录。还有一个帮手checkThenSet
方法实际上是最常见的模式,检查我们是否可以做某事,
并创造了我们所做的记录。
用法
(用例) 如果您的应用正在发送电子邮件,您不会希望通过以下方式发送相同的电子邮件
一遍又一遍,即使用户触发了它。
// on server
if (!Throttle.checkThenSet(key, allowedCount, expireInSec)) {
throw new Meteor.Error(500, 'You may only send ' + allowedCount + ' emails at a time, wait a while and try again');
}
....
关于节流方法
-
checkThenSet(key, allowedCount, expireInSec) 检查密钥,如果通过,则设置密钥以供将来检查
-
check(key, allowedCount) 检查一个键,如果存在的(未过期)记录少于 allowedCount,则通过
-
set(key, expireInSec)为key设置了一条记录,在expireInSec秒后过期,例如:60=1分钟后
-
purge() 过期所有不再在时间范围内的记录(每次检查时自动调用)
方法(可调用)
-
throttle(key, allowedCount, expireInSec) --> Throttle.checkThenSet()
-
throttle-check(key, allowedCount) --> Throttle.check()
-
throttle-set(key, expireInSec) --> Throttle.set()