feat: QPS Limit middleware (#2956)

* feat: QPS Limit middleware

* chore: use request-ip to get client ip

* feat: frequencyLimit schema
This commit is contained in:
Finley Ge
2024-10-25 10:08:59 +08:00
committed by shilin66
parent 23326b80a6
commit 1b3dccc543
8 changed files with 144 additions and 28 deletions

View File

@@ -0,0 +1,32 @@
import { AuthFrequencyLimitProps } from '@fastgpt/global/common/frequenctLimit/type';
import { MongoFrequencyLimit } from './schema';
import { readFromSecondary } from '../../mongo/utils';
export const authFrequencyLimit = async ({
eventId,
maxAmount,
expiredTime
}: AuthFrequencyLimitProps) => {
try {
// 对应 eventId 的 account+1, 不存在的话,则创建一个
const result = await MongoFrequencyLimit.findOneAndUpdate(
{
eventId
},
{
$inc: { amount: 1 },
$setOnInsert: { expiredTime }
},
{
upsert: true,
new: true,
...readFromSecondary
}
);
// 因为始终会返回+1的结果所以这里不能直接等需要多一个。
if (result.amount > maxAmount) {
return Promise.reject(result);
}
} catch (error) {}
};