forked from ping-pub/faucet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecker.js
46 lines (40 loc) · 1.25 KB
/
checker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { Level } from "level";
const WINDOW = 86400 * 1000 // milliseconds in a day
// const WINDOW = 20 * 1000 // 20s for test
export class FrequencyChecker {
constructor(conf) {
this.conf = conf
this.db = new Level(conf.db.path, { valueEncoding: 'json' });
}
async check(key, limit) {
return new Promise((resolve) => {
this.db.get(key, function (err, value) {
const now = Date.now()
if (err || value && value.filter(x => now - x < WINDOW).length < limit) {
resolve(true)
// console.log(key, limit, value, true)
} else {
resolve(false)
// console.log(key, limit, false)
}
});
})
}
async checkIp(ip) {
return this.check(ip, this.conf.limit.ip)
}
async checkAddress(address) {
return this.check(address, this.conf.limit.address)
}
async update(key) {
const db = this.db
db.get(key, function (err, history) {
if (err) {
db.put(key, [Date.now()])
} else {
history.push(Date.now())
db.put(key, history)
}
});
}
}