npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ahmadyusri/adonis-request-throttler

v2.0.8

Published

Request throttler provider for AdonisJS 5

Downloads

7

Readme

Adonis-Request-Throttler

Request limiter for Adonis JS 5 Fork from adonis-request-throttler

typescript-image npm-image license-image

Table of contents

Installation

Install Adonis redis client, if you want to use redis as storage for request info.

npm i --save @ahmadyusri/adonis-request-throttler

Install provider:

node ace configure @ahmadyusri/adonis-request-throttler
  • For other configuration, please update the config/request-throttler.ts.

Sample Usage

Throttler middleware

After adding request throttler to your app, you must register the middleware.

// start/kernel.ts
Server.middleware.registerNamed({
  throttle: 'Adonis/Addons/RequestThrottler/Middleware'
})

And then you can add middleware to your routes:

Route
  .get('subscribers', 'SubscriberController.index')
  .middleware('throttle')

This middleware will limit user requests to endpoint. Configure default count and timeout in throttle config. For custom configuration you can add values as middleware params:

Route
  .get('subscribers', 'SubscriberController.index')
  .middleware('throttle:10,20')

First param is responsible for max attempt count, second params means time limit after exceeding the quota.

Throttler service

You can also use throttler in your services by client identifier:

import RequestThrottler from '@ioc:Adonis/Addons/RequestThrottler'

RequestThrottler.verifyClient(userId, 10, 15)

Or you can verify request in your controller:

import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import RequestThrottler from '@ioc:Adonis/Addons/RequestThrottler'

export default class ControllerExample {
  public async index({ request }: HttpContextContract) {
    await RequestThrottler.verifyRequest(request)

    return // endpoint data
  }
}

Configuration

For configuring request throttler use request-throttler.ts file in config dir.

import { ThrottleConfig } from '@ioc:Adonis/Addons/RequestThrottler'

export default {
	maxAttempts: 10,

	maxAttemptPeriod: 600000,

	ttlUnits: 'ms',

	cacheStorage: 'redis',

	useOwnCache: true,

	limitExceptionParams: {
		code: 'E_LIMIT_EXCEPTION',
		message: 'Maximum number of login attempts exceeded.',
		status: 429,
	},

	requestKeysForRecognizing: ['method', 'hostname', 'url', 'ip'],
} as ThrottleConfig

You can configure such options:

  • maxAttempts - permitted request count for user for permitted request count

  • maxAttemptPeriod - specify ttl for record, which store info about last user request

  • ttlUnits - time units for maxAttemptPeriod property

  • cacheStorage - specify storage for requests information

  • useOwnCache - specify is request throttler uses own cache provider or takes already instantiated cache provider from Adonis IoC container

  • limitExceptionParams - specify params for limit exception, you can change http status or add localization for message

  • requestKeysForRecognizing - specify request keys for recognizing the client and the route

Request recognizer

By default for request verifying throttler takes info about method, hostname, url, ip of request. If you need to specify request recognizing you should implement ClientRecognizerContract interface in your custom recognizer.

import { RequestContract } from '@ioc:Adonis/Core/Request'
import { ClientRecognizerContract } from '@ioc:Adonis/Addons/RequestThrottler'

export default class CustomClientRecognizer implements ClientRecognizerContract {
	public identifyClient(request: RequestContract): Promise<string> | string {
		return // client-identifier
	}
}

And then you should register your recognizer. For example you can do it in this way:

import RequestThrottler from '@ioc:Adonis/Addons/RequestThrottler'

RequestThrottler.useClientRecognizer(new CustomClientRecognizer())

Then your requests will recognize using your custom recognizer.

Cache storage

This packages based on adonis cache package. Throttler can work in two modes. By default throttler creates own cache client and uses it for storing info about requests. If you use Adonis cache you can use already instantiated provider for throttler. For using adonis cache set false to useOwnCache parameter in your throttler config.

You need the same ttlUnits in your cache and request-throttler config.

You should register cache provider before request-throttler:

{
"providers": [
    "./providers/AppProvider",
    "@adonisjs/core",
    "@adonisjs/lucid",
    "@adonisjs/redis",
    "adonis5-cache",
    "adonis-request-throttler"
  ]
}

When you use adonis5-cache as storage, you can add custom storages for storing request data. Read more about this in adonis5-cache docs.