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,26 @@
import { ApiRequestProps } from 'type/next';
import requestIp from 'request-ip';
import { ERROR_ENUM } from '@fastgpt/global/common/error/errorCode';
import { authFrequencyLimit } from 'common/system/frequencyLimit/utils';
import { addSeconds } from 'date-fns';
// unit: times/s
// how to use?
// export default NextAPI(useQPSLimit(10), handler); // limit 10 times per second for a ip
export function useQPSLimit(limit: number) {
return async (req: ApiRequestProps) => {
const ip = requestIp.getClientIp(req);
if (!ip) {
return;
}
try {
await authFrequencyLimit({
eventId: 'ip-qps-limit' + ip,
maxAmount: limit,
expiredTime: addSeconds(new Date(), 1)
});
} catch (_) {
return Promise.reject(ERROR_ENUM.QPSLimitExceed);
}
};
}