43 lines
756 B
JavaScript
43 lines
756 B
JavaScript
class MemoryStore {
|
|
constructor(clearPeriod) {
|
|
this.hits = new Map()
|
|
setInterval(this.reset.bind(this), clearPeriod)
|
|
}
|
|
|
|
incr(key) {
|
|
let counter = this.hits.get(key) || 0
|
|
counter++
|
|
this.hits.set(key, counter)
|
|
return counter
|
|
}
|
|
|
|
reset() {
|
|
this.hits.clear()
|
|
}
|
|
}
|
|
|
|
const limit = options => {
|
|
const config = Object.assign(
|
|
{
|
|
window: 1000,
|
|
limit: 1,
|
|
keyGenerator: ctx => {
|
|
return ctx.from && ctx.from.id
|
|
},
|
|
onLimitExceeded: () => {}
|
|
},
|
|
options
|
|
)
|
|
|
|
const store = new MemoryStore(config.window)
|
|
|
|
return (ctx, next) => {
|
|
const key = config.keyGenerator(ctx)
|
|
if (!key) return next()
|
|
const hit = store.incr(key)
|
|
return hit <= config.limit ? next() : config.onLimitExceeded(ctx, next)
|
|
}
|
|
}
|
|
|
|
module.exports = limit
|