Git Product home page Git Product logo

adonis-request-throttler's Introduction

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.

adonis-request-throttler's People

Contributors

vladyslavparashchenko avatar reg2005 avatar ahmadyusri avatar kevinrouchut avatar evoactivity avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.