-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Expand file tree
/
Copy pathutils.ts
More file actions
42 lines (39 loc) · 1.18 KB
/
utils.ts
File metadata and controls
42 lines (39 loc) · 1.18 KB
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
import { type AuthFrequencyLimitProps } from '@fastgpt/global/common/frequenctLimit/type';
import { ERROR_ENUM } from '@fastgpt/global/common/error/errorCode';
import { MongoFrequencyLimit } from './schema';
import { getLogger, LogCategories } from '../../logger';
const logger = getLogger(LogCategories.SYSTEM);
export const authFrequencyLimit = async ({
eventId,
maxAmount,
expiredTime,
num = 1
}: AuthFrequencyLimitProps) => {
try {
// 对应 eventId 的 account+1, 不存在的话,则创建一个
const result = await MongoFrequencyLimit.findOneAndUpdate(
{
eventId,
expiredTime: { $gte: new Date() }
},
{
$inc: { amount: num },
// If not exist, set the expiredTime
$setOnInsert: { expiredTime }
},
{
upsert: true,
new: true
}
).lean();
// 因为始终会返回+1的结果,所以这里不能直接等,需要多一个。
if (result.amount > maxAmount) {
throw ERROR_ENUM.tooManyRequest;
}
} catch (error) {
if (error === ERROR_ENUM.tooManyRequest) {
throw error;
}
logger.error('Failed to update auth frequency limit', { eventId, error });
}
};