mirror of
https://github.com/hansputera/tiktok-dl.git
synced 2026-04-05 19:51:57 +02:00
feat(apps.web.middleware#ratelimit): return HttpErrclass or instead than send a response
Signed-off-by: Hanif Dwy Putra S <47862061+hansputera@users.noreply.github.com>
This commit is contained in:
@@ -1,28 +1,26 @@
|
||||
import type {NextApiRequest, NextApiResponse} from 'next';
|
||||
import {rateLimitConfig} from '../config';
|
||||
import {HttpError} from '../errors';
|
||||
import {client} from '../lib';
|
||||
|
||||
export const ratelimitMiddleware = async (
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
_res: NextApiResponse,
|
||||
) => {
|
||||
const ip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'];
|
||||
if (!rateLimitConfig.enable || process.env.NODE_ENV === 'development')
|
||||
return true;
|
||||
else if (!ip) {
|
||||
return res
|
||||
.status(401)
|
||||
.json({message: "Couldn't find your real ip address."});
|
||||
}
|
||||
return undefined;
|
||||
else if (!ip)
|
||||
throw new HttpError("Couldn't find your real ip address!").setCode(401);
|
||||
const result = await client.get('rate-'.concat(ip.toString()));
|
||||
if (result) {
|
||||
if (parseInt(result) > rateLimitConfig.maxRatelimitPerXSeconds) {
|
||||
return res.status(429).json({
|
||||
message: 'Please try again, you are getting ratelimit!',
|
||||
});
|
||||
throw new HttpError(
|
||||
'Please try again, you are getting ratelimit!',
|
||||
).setCode(429);
|
||||
}
|
||||
client.incr('rate-'.concat(ip.toString()));
|
||||
return true;
|
||||
return undefined;
|
||||
} else {
|
||||
client.set(
|
||||
'rate-'.concat(ip.toString()),
|
||||
@@ -30,6 +28,6 @@ export const ratelimitMiddleware = async (
|
||||
'EX',
|
||||
rateLimitConfig.ratelimitTime,
|
||||
);
|
||||
return true;
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user