Created
May 2, 2021 14:12
-
-
Save Caballerog/afb4e7a0323a5707d3bb3b239b24ce76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Middleware } from "./middleware"; | |
import { User } from "../interfaces"; | |
import { WAIT_TIME } from "../app.constants"; | |
export class ThrottlingMiddleware extends Middleware { | |
private request: number = 0; | |
private currentTime: number = new Date().getTime(); | |
private requestPerMinute: number; | |
constructor(requestPerMinute: number) { | |
super(); | |
this.requestPerMinute = requestPerMinute; | |
} | |
public execute(user: User): boolean { | |
const now = new Date().getTime(); | |
const limitTime = this.currentTime + WAIT_TIME; | |
if (now > limitTime) { | |
this.request = 0; | |
this.currentTime = now; | |
} | |
this.request++; | |
if (this.request > this.requestPerMinute) { | |
console.log("Request limit exceeded!"); | |
return false; | |
} | |
return this.checkNext(user); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment