diff --git a/.gitignore b/.gitignore index e9d079f..b9cd518 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/.idea/ node_modules/ package-lock.json *.tsbuildinfo diff --git a/src/rateLimiter.ts b/src/rateLimiter.ts index e05611c..afa8069 100644 --- a/src/rateLimiter.ts +++ b/src/rateLimiter.ts @@ -34,14 +34,15 @@ export const limit = ( ? new MemoryStore(options.timeFrame) : new RedisStore(options.storageClient as RT, options.timeFrame); + const keyPrefix = userOptions?.keyPrefix ?? defaultOptions.keyPrefix; + const middlewareFunc = async (ctx: C, next: NextFunction) => { - const keyCheck = options.keyGenerator(ctx); - if (!keyCheck) { + const key = options.keyGenerator(ctx); + if (!key) { return await next(); } - const key = "RATE_LIMITER" + keyCheck; - const hits = await store.increment(key); + const hits = await store.increment(keyPrefix + key); if (hits === options.limit + 1 || (options.alwaysReply && hits > options.limit)) { return options.onLimitExceeded(ctx, next); diff --git a/src/typesAndDefaults.ts b/src/typesAndDefaults.ts index 66ba278..9f878e1 100644 --- a/src/typesAndDefaults.ts +++ b/src/typesAndDefaults.ts @@ -54,17 +54,35 @@ export interface OptionsInterface { /** * @param ctx Is the context object you get from grammy/telegraf. - * @returns A number in **string** format as the unique key (identifier). - * @description A function to generate a unique key for every user. You cound set it as any key you want (e.g group id) + * @returns A unique **string** key (identifier). + * @description A function to generate a unique key for every user. You could set it as any key you want (e.g. group id) * @see [Getting Started](https://github.com/Amir-Zouerami/rateLimiter#-how-to-use) */ keyGenerator?: (ctx: C) => string | undefined; + + /** + * @default "RATE_LIMITER" + * @description A string prefix that is getting added to the storage key after calling the `keyGenerator()`. + */ + keyPrefix?: string | undefined; } -export const defaultOptions = { +type DefaultOptions = Required, ( + | 'timeFrame' + | 'limit' + | 'onLimitExceeded' + | 'storageClient' + | 'keyGenerator' + | 'keyPrefix' + )> +>; + +export const defaultOptions: DefaultOptions = { timeFrame: 1000, limit: 1, onLimitExceeded: (_ctx: Context, _next: NextFunction) => {}, storageClient: "MEMORY_STORE", - keyGenerator: (ctx: Context) => ctx.from === undefined ? undefined : ctx.from.id.toString(), + keyGenerator: (ctx: Context) => ctx.from?.id.toString(), + keyPrefix: "RATE_LIMITER", };