@domain.js/main 0.3.14 → 0.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -6,9 +6,10 @@ interface Cnf {
|
|
|
6
6
|
}
|
|
7
7
|
export declare const Deps: readonly ["redis"];
|
|
8
8
|
interface Deps {
|
|
9
|
-
redis: Pick<Redis, "hincrby" | "expire">;
|
|
9
|
+
redis: Pick<Redis, "hincrby" | "expire" | "hget" | "hdel">;
|
|
10
10
|
}
|
|
11
11
|
export declare function Main(cnf: Cnf, deps: Deps): {
|
|
12
|
+
control: (filed: string, ms: number, limit: number) => Promise<void>;
|
|
12
13
|
check: (filed: string, ms: number, limit: number) => Promise<void>;
|
|
13
14
|
};
|
|
14
15
|
export {};
|
|
@@ -6,23 +6,51 @@ function Main(cnf, deps) {
|
|
|
6
6
|
const { redis } = deps;
|
|
7
7
|
const { frequency: { key: KEY }, } = cnf;
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
9
|
+
* 计算应该的key
|
|
10
|
+
* @param ms 频率控制长度,单位毫秒
|
|
11
|
+
*/
|
|
12
|
+
const getKey = (ms) => {
|
|
13
|
+
const now = Date.now();
|
|
14
|
+
const t = Math.floor(now / ms);
|
|
15
|
+
return `${KEY}-${ms}-${t}`;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* 计算过期时间
|
|
19
|
+
* @param ms 频率控制长度,单位毫秒
|
|
20
|
+
*/
|
|
21
|
+
const expire = (ms) => {
|
|
22
|
+
const now = Date.now();
|
|
23
|
+
const t = Math.floor(now / ms);
|
|
24
|
+
return Math.floor((ms * (t + 1) - now) / 1000);
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* 频次控制,超过显示过抛出异常
|
|
10
28
|
* @param filed 控频字段key
|
|
11
29
|
* @param ms 控频周期长度 毫秒
|
|
12
30
|
* @param limit 控频极限次数
|
|
13
31
|
*/
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const t = Math.floor(now / ms);
|
|
17
|
-
const key = `${KEY}-${ms}-${t}`;
|
|
32
|
+
const control = async (filed, ms, limit) => {
|
|
33
|
+
const key = getKey(ms);
|
|
18
34
|
const val = await redis.hincrby(key, filed, 1);
|
|
19
35
|
if (val === 1)
|
|
20
|
-
await redis.expire(key,
|
|
36
|
+
await redis.expire(key, expire(ms));
|
|
21
37
|
if (val > limit)
|
|
22
38
|
throw Error("Too many request");
|
|
23
39
|
};
|
|
24
|
-
|
|
25
|
-
|
|
40
|
+
/**
|
|
41
|
+
* 检测频次控制,超过显示过抛出异常
|
|
42
|
+
* @param filed 控频字段key
|
|
43
|
+
* @param ms 控频周期长度 毫秒
|
|
44
|
+
* @param limit 控频极限次数
|
|
45
|
+
*/
|
|
46
|
+
const check = async (filed, ms, limit) => {
|
|
47
|
+
const key = getKey(ms);
|
|
48
|
+
const val = await redis.hget(key, filed);
|
|
49
|
+
if (!val)
|
|
50
|
+
return;
|
|
51
|
+
if ((Number(val) | 0) > limit)
|
|
52
|
+
throw Error("Too many request");
|
|
26
53
|
};
|
|
54
|
+
return { control, check };
|
|
27
55
|
}
|
|
28
56
|
exports.Main = Main;
|