(seconds: number, errMsg?: string)
| 8 | const SPEED_LIMIT_KEY = "SpeedLimit"; |
| 9 | |
| 10 | export function speedLimit(seconds: number, errMsg?: string) { |
| 11 | return async (ctx: Context, next: Function) => { |
| 12 | const requestPath = ctx.URL.pathname; |
| 13 | const user = getUserFromCtx(ctx); |
| 14 | |
| 15 | if (!user) throw new Error($t("TXT_CODE_permission.forbidden")); |
| 16 | |
| 17 | if (user.permission === ROLE.ADMIN) { |
| 18 | return await next(); |
| 19 | } |
| 20 | |
| 21 | const speedCheckKey = `${SPEED_LIMIT_KEY}:${user.uuid}:${requestPath}`; |
| 22 | const isExist = singletonMemoryRedis.get<boolean>(speedCheckKey); |
| 23 | |
| 24 | if (isExist) { |
| 25 | ctx.status = 500; |
| 26 | ctx.body = |
| 27 | errMsg || |
| 28 | $t("TXT_CODE_c093bec9", { |
| 29 | seconds: singletonMemoryRedis.ttl(speedCheckKey) |
| 30 | }); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | singletonMemoryRedis.set(speedCheckKey, true, seconds); |
| 35 | return await next(); |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | export function requestConcurrencyLimiter(url: string) { |
| 40 | return async (ctx: Context, next: Function) => { |
no test coverage detected