UNPKG

@adonisjs/limiter

Version:

Rate limiting package for AdonisJS framework

84 lines (83 loc) 3.01 kB
import { RateLimiterRes, type RateLimiterAbstract, type RateLimiterStoreAbstract } from 'rate-limiter-flexible'; import { LimiterResponse } from '../response.js'; import type { LimiterStoreContract } from '../types.js'; /** * The bridget store acts as a bridge between the "rate-limiter-flexible" * package and the AdonisJS limiter store. * * If you are wrapping an existing "rate-limiter-flexible" store, then you * must inherit your implementation from this class. */ export default abstract class RateLimiterBridge implements LimiterStoreContract { protected rateLimiter: RateLimiterStoreAbstract | RateLimiterAbstract; /** * A unique name for the store */ abstract readonly name: string; /** * The number of configured requests on the store */ get requests(): number; /** * The duration (in seconds) for which the requests are configured */ get duration(): number; /** * The duration (in seconds) for which to block the key */ get blockDuration(): number; constructor(rateLimiter: RateLimiterStoreAbstract | RateLimiterAbstract); /** * Clear database */ abstract clear(): Promise<void>; /** * Makes LimiterResponse from "node-rate-limiter-flexible" response * object */ protected makeLimiterResponse(response: RateLimiterRes): LimiterResponse; /** * Consume 1 request for a given key. An exception is raised * when all the requests have already been consumed or if * the key is blocked. */ consume(key: string | number): Promise<LimiterResponse>; /** * Increment the number of consumed requests for a given key. * No errors are thrown when limit has reached */ increment(key: string | number): Promise<LimiterResponse>; /** * Decrement the number of consumed requests for a given key. */ decrement(key: string | number): Promise<LimiterResponse>; /** * Block a given key for the given duration. The duration must be * a value in seconds or a string expression. */ block(key: string | number, duration: string | number): Promise<LimiterResponse>; /** * Manually set the number of requests exhausted for * a given key for the given time duration. * * For example: "ip_127.0.0.1" has made "20 requests" in "1 minute". * Now, if you allow 25 requests in 1 minute, then only 5 requests * are left. * * The duration must be a value in seconds or a string expression. */ set(key: string | number, requests: number, duration?: string | number): Promise<LimiterResponse>; /** * Delete a given key */ delete(key: string | number): Promise<boolean>; /** * Delete all keys blocked within the memory */ deleteInMemoryBlockedKeys(): void; /** * Get limiter response for a given key. Returns null when * key doesn't exist. */ get(key: string | number): Promise<LimiterResponse | null>; }