Guest User

Untitled

a guest
Mar 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. /**
  2. * Increment and get the number of request
  3. * per defined interval (currently 1 seconds)
  4. *
  5. * @param key to use for request rate counting
  6. *
  7. * @return promise object returning the request rate
  8. */
  9. function incrementRequestRate( key ) {
  10. // Redis request interval in milliseconds
  11. // (currently set as 1 second)
  12. let reqInterval = 1000;
  13.  
  14. // Lets increment and get the request rate
  15. // Inside a promise
  16. let reqPromise = redisClient.incr( key );
  17.  
  18. //
  19. // asynchronously set the expiry
  20. // in the background.
  21. //
  22. // In practise due to the "delay" between
  23. // the increment, and the ttl get+expire set,
  24. // the request interval is slightly larger than
  25. // the value configured for "reqInterval"
  26. //
  27. reqPromise.then(function() {
  28. // Get the current value, ttl in milliseconds
  29. // which is -1, if its not configured
  30. redisClient.pttl( key ).then(function(ttlValue) {
  31. if( ttlValue == -1 ) {
  32. // ttl expiry is not configure,
  33. // configure it to be reqInterval
  34. redisClient.pexpire( key, reqInterval );
  35. }
  36. });
  37. });
  38.  
  39. // Lets return the promise with the result
  40. return reqPromise;
  41. }
  42.  
  43. /**
  44. * Increment and get the number of request
  45. * per defined interval (currently 1 seconds).
  46. *
  47. * Throws an exception inside the promise if the rate limit is reached.
  48. *
  49. * @param key to use for request rate counting
  50. * @param limit to the number of request per interval (seconds) supported.
  51. * (optional, defaults to 10)
  52. *
  53. * @return promise object, returning either the request rate
  54. * (if below the limit), or an error
  55. */
  56. function applyRequestRateLimit( key, limit ) {
  57. // Normalize the limit to default value if not set
  58. limit = limit || 10;
  59.  
  60. // Increment the request rate,
  61. // and respond accordingly
  62. return incrementRequestRate(key).then(function(rate) {
  63. if( rate > limit ) {
  64. throw "request rate limit reached";
  65. }
  66. return rate;
  67. });
  68. }
Add Comment
Please, Sign In to add comment