Welcome to our second court challenge.
So let's see what we are going to do.
It says that create a middleware function that will check the number of requests made to the server.
And if the number of requests is greater than ten return response, we start this code 4 to 9, which
means too many requests.
And if the number of requests is less than ten, we are going to call the next million word.
So what we are going to do is that we are going to check how many requests has been made to our server.
So by default we are going to allow only ten requests to the server.
If a user make more than ten requests, we are going to through an error, say, is that too many requests?
All right.
Give it a shot.
Welcome back.
Now let me show you my solution.
So here we go.
Solution four, challenge number two.
So the first step is I need to declare a variable that's going to keep track the number of requests.
So I make use of LED because I won't override the value for this variable.
So the variable name going to be as request count and by default I'll assign as zero.
So now here comes our middle word.
So cost.
Request count.
Is equal to arrow function.
So let me change this one to request count value I start and for the function I have access to my request
response and then the next.
So inside my function body, I'm going to check if the request value count is more than ten.
So inside the if statement, you are going to throw an error with status code for two nine, which means
too many requests.
So here we are going to return from this function and now on rest.
Then we add a status code.
Status code, and then I start 4 to 9 and next is the message.
Let's use JSON data here and you provide too many.
Request a house.
Go ahead and then call next as that.
Now.
Moment of truth.
So let me pass this one to app dot use because I want to provide this one to all of the route.
So I'm going to be request counts.
So inside the request.
So inside the request counts, let's try to console.log the value in the console and see how many counts
we have made to the server.
So request count value.
So now I'm back to Postman.
Well, I see.
Zero.
Why is it so?
The problem is that we are not updating the counts.
Sorry, guys.
So inside the body here for each request, you are going to update the value that is plus plus with
plus one.
So now with this one, our server has restarted.
Let me make the request.
The first one, I get one here.
Second I get two and three, four or five until I hit more than 20 or ten.
And let's see.
Let me check.
I see ten here.
The last one going to be you see, I get a message.
Too many requests.