rate-limiter-flexible#RateLimiterRes TypeScript Examples

The following examples show how to use rate-limiter-flexible#RateLimiterRes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: proxy.ts    From NanoRPCProxy with GNU General Public License v3.0 6 votes vote down vote up
rateLimiterMiddleware2 = (req: Request, res: Response, next: (err?: any) => any) => {
  limiter2.consume(req.ip, 1)
    .then((response: RateLimiterRes) => {
      next()
    })
    .catch((error?: Error) => {
      promClient?.incDDOS(req.ip)
      res.status(429).send('You are making requests too fast, please slow down!')
    })
 }
Example #2
Source File: limiterGroup.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/**
   * Handle rejection from limiter
   *
   * @param {Error|RateLimiterRes} error
   * @returns {RateLimiterRes}
   */
  static handleRejection(error): RateLimiterRes {
    if (isError(error)) {
      throw error;
    }

    return error;
  }
Example #3
Source File: limiterGroup.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/**
   * Get limit result from response
   *
   * @param {RateLimiterRes|null} response
   * @param {Limiter} limiter
   * @returns {LimitResultInterface}
   */
  static getLimitResult(response: RateLimiterRes | null, limiter: Limiter): LimitResultInterface {
    const blocked = response && response.consumedPoints >= limiter.max;

    return {
      name: limiter.name,
      limit: limiter.max,
      remaining: response?.remainingPoints || limiter.max,
      // eslint-disable-next-line no-magic-numbers
      resetMs: response?.msBeforeNext || limiter.blockDurationSec * 1000,
      blockReason: blocked ? limiter.reason : null,
    };
  }
Example #4
Source File: limiterGroup.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/* eslint-disable sonarjs/cognitive-complexity */
  /**
   * Reduce results to most relevant
   *
   * @param {any} results
   * @param {LimitResultInterface} [curLimitResult]
   * @returns {LimitResultInterface}
   */
  static reduceLimitResults(
    results: { response: RateLimiterRes | null; limiter: Limiter }[],
    curLimitResult?: LimitResultInterface
  ): LimitResultInterface {
    if (results.length === 0) throw new Err('results empty');

    return results.reduce((result, { response, limiter }) => {
      const limitResult = LimiterGroup.getLimitResult(response, limiter);

      if (!result) return limitResult;
      if (result.blockReason && !limitResult.blockReason) return result;
      if (!result.blockReason && limitResult.blockReason) return limitResult;
      if (result.remaining !== limitResult.remaining) {
        return result.remaining < limitResult.remaining ? result : limitResult;
      }
      if (result.resetMs !== limitResult.resetMs) {
        return result.resetMs < limitResult.resetMs ? limitResult : result;
      }
      return result;
    }, curLimitResult || LimiterGroup.getLimitResult(results[0].response, results[0].limiter));
  }
Example #5
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
consume(key, pointsToConsume = 1, options = {}) {
    return new Promise<RateLimiterRes>((resolve, reject) => {
      this.ipcClient.send(
        'consume',
        [
          this.keyPrefix,
          JSON.stringify({
            key,
            pointsToConsume,
            options
          })
        ],
        res => workerProcessResponse.call(this, res, resolve, reject)
      )
    })
  }
Example #6
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
penalty(key, points = 1, options = {}) {
    return new Promise<RateLimiterRes>((resolve, reject) => {
      this.ipcClient.send(
        'penalty',
        [
          this.keyPrefix,
          JSON.stringify({
            key,
            points,
            options
          })
        ],
        res => workerProcessResponse.call(this, res, resolve, reject)
      )
    })
  }
Example #7
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
reward(key, points = 1, options = {}) {
    return new Promise<RateLimiterRes>((resolve, reject) => {
      this.ipcClient.send(
        'reward',
        [
          this.keyPrefix,
          JSON.stringify({
            key,
            points,
            options
          })
        ],
        res => workerProcessResponse.call(this, res, resolve, reject)
      )
    })
  }
Example #8
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
block(key, secDuration, options = {}) {
    return new Promise<RateLimiterRes>((resolve, reject) => {
      this.ipcClient.send(
        'block',
        [
          this.keyPrefix,
          JSON.stringify({
            key,
            secDuration,
            options
          })
        ],
        res => workerProcessResponse.call(this, res, resolve, reject)
      )
    })
  }
Example #9
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
get(key, options = {}) {
    return new Promise<RateLimiterRes>((resolve, reject) => {
      this.ipcClient.send(
        'get',
        [
          this.keyPrefix,
          JSON.stringify({
            key,
            options
          })
        ],
        res => workerProcessResponse.call(this, res, resolve, reject)
      )
    })
  }
Example #10
Source File: rate-limiter-ipc.ts    From notabug with MIT License 6 votes vote down vote up
workerProcessResponse = function(
  msg,
  resolve: Function,
  reject: Function
) {
  if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {
    return false
  }

  let res
  if (msg.data === null || msg.data === true || msg.data === false) {
    res = msg.data
  } else {
    res = new RateLimiterRes(
      msg.data.remainingPoints,
      msg.data.msBeforeNext,
      msg.data.consumedPoints,
      msg.data.isFirstInDuration // eslint-disable-line comma-dangle
    )
  }

  switch (msg.type) {
    case 'resolve':
      resolve(res)
      break
    case 'reject':
      reject(res)
      break
    default:
      throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`)
  }

  return undefined
}