Last active
June 4, 2018 03:41
-
-
Save claustres/70bef1376a19ed18fa234205d52e8ab7 to your computer and use it in GitHub Desktop.
Rate limiting with FeathersJS - Concurrent
This file contains hidden or 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 { TooManyRequests } from 'feathers-errors' | |
import { RateLimiter } from 'limiter' | |
import makeDebug from 'debug' | |
const debug = makeDebug('debug') | |
export function rateLimit (options) { | |
const limiter = new RateLimiter(options.tokensPerInterval, options.interval) | |
return function (hook) { | |
if (hook.type !== 'before') { | |
throw new Error(`The 'rateLimit' hook should only be used as a 'before' hook.`) | |
} | |
let rateLimit = true | |
if (options.operation && (options.operation !== hook.method)) { | |
rateLimit = false | |
} | |
if (rateLimit) { | |
debug(limiter.getTokensRemaining() + ' remaining token for rateLimit hook on service') | |
if (!limiter.tryRemoveTokens(1)) { // if exceeded | |
throw new TooManyRequests('Too many requests in a given amount of time (rate limiting) on service ') | |
} | |
} | |
return hook | |
} | |
} | |
// When configuring the service | |
service.hooks({ | |
before: { | |
all: [ rateLimit({ tokensPerInterval: 5, interval: 60 * 1000, method: 'create' }) ] // 5 calls per minute | |
create: [ rateLimit({ tokensPerInterval: 5, interval: 60 * 1000 }) ] // Similar as previous | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment