UNPKG

@adonisjs/limiter

Version:

Rate limiting package for AdonisJS framework

85 lines (83 loc) 3.13 kB
import { RateLimiterBridge, debug_default } from "../../chunk-RWNA5JOS.js"; import "../../chunk-MLKGABMK.js"; // src/stores/database.ts import string from "@adonisjs/core/helpers/string"; import { RuntimeException } from "@adonisjs/core/exceptions"; import { RateLimiterMySQL, RateLimiterPostgres } from "rate-limiter-flexible"; var LimiterDatabaseStore = class extends RateLimiterBridge { #config; #client; get name() { return "database"; } constructor(client, config) { const dialectName = client.dialect.name; if (dialectName !== "mysql" && dialectName !== "postgres") { throw new RuntimeException( `Unsupported database "${dialectName}". The limiter can only work with PostgreSQL and MySQL databases` ); } debug_default("creating %s limiter store %O", dialectName, config); switch (dialectName) { case "mysql": super( new RateLimiterMySQL({ storeType: "knex", storeClient: client.getWriteClient(), tableCreated: true, dbName: config.dbName, tableName: config.tableName, keyPrefix: config.keyPrefix, execEvenly: config.execEvenly, points: config.requests, clearExpiredByTimeout: config.clearExpiredByTimeout, duration: string.seconds.parse(config.duration), inMemoryBlockOnConsumed: config.inMemoryBlockOnConsumed, blockDuration: config.blockDuration ? string.seconds.parse(config.blockDuration) : void 0, inMemoryBlockDuration: config.inMemoryBlockDuration ? string.seconds.parse(config.inMemoryBlockDuration) : void 0 }) ); this.#client = client; this.#config = config; break; case "postgres": super( new RateLimiterPostgres({ storeType: "knex", schemaName: config.schemaName, storeClient: client.getWriteClient(), tableCreated: true, dbName: config.dbName, tableName: config.tableName, keyPrefix: config.keyPrefix, execEvenly: config.execEvenly, points: config.requests, clearExpiredByTimeout: config.clearExpiredByTimeout, duration: string.seconds.parse(config.duration), inMemoryBlockOnConsumed: config.inMemoryBlockOnConsumed, blockDuration: config.blockDuration ? string.seconds.parse(config.blockDuration) : void 0, inMemoryBlockDuration: config.inMemoryBlockDuration ? string.seconds.parse(config.inMemoryBlockDuration) : void 0 }) ); this.#client = client; this.#config = config; break; } } /** * Deletes all rows from the database table. Make sure to * use separate database tables for every rate limiter * your configure. */ async clear() { debug_default("truncating database table %s", this.#config.tableName); this.deleteInMemoryBlockedKeys(); await this.#client.dialect.truncate(this.#config.tableName, true); } }; export { LimiterDatabaseStore as default };