Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Increment and get the number of request
- * per defined interval (currently 1 seconds)
- *
- * @param key to use for request rate counting
- *
- * @return promise object returning the request rate
- */
- function incrementRequestRate( key ) {
- // Redis request interval in milliseconds
- // (currently set as 1 second)
- let reqInterval = 1000;
- // Lets increment and get the request rate
- // Inside a promise
- let reqPromise = redisClient.incr( key );
- //
- // asynchronously set the expiry
- // in the background.
- //
- // In practise due to the "delay" between
- // the increment, and the ttl get+expire set,
- // the request interval is slightly larger than
- // the value configured for "reqInterval"
- //
- reqPromise.then(function() {
- // Get the current value, ttl in milliseconds
- // which is -1, if its not configured
- redisClient.pttl( key ).then(function(ttlValue) {
- if( ttlValue == -1 ) {
- // ttl expiry is not configure,
- // configure it to be reqInterval
- redisClient.pexpire( key, reqInterval );
- }
- });
- });
- // Lets return the promise with the result
- return reqPromise;
- }
- /**
- * Increment and get the number of request
- * per defined interval (currently 1 seconds).
- *
- * Throws an exception inside the promise if the rate limit is reached.
- *
- * @param key to use for request rate counting
- * @param limit to the number of request per interval (seconds) supported.
- * (optional, defaults to 10)
- *
- * @return promise object, returning either the request rate
- * (if below the limit), or an error
- */
- function applyRequestRateLimit( key, limit ) {
- // Normalize the limit to default value if not set
- limit = limit || 10;
- // Increment the request rate,
- // and respond accordingly
- return incrementRequestRate(key).then(function(rate) {
- if( rate > limit ) {
- throw "request rate limit reached";
- }
- return rate;
- });
- }
Add Comment
Please, Sign In to add comment