Skip to content

Instantly share code, notes, and snippets.

@claustres
Last active June 4, 2018 03:41
Show Gist options
  • Save claustres/70bef1376a19ed18fa234205d52e8ab7 to your computer and use it in GitHub Desktop.
Save claustres/70bef1376a19ed18fa234205d52e8ab7 to your computer and use it in GitHub Desktop.
Rate limiting with FeathersJS - Concurrent
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