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..ea0c002 100644 --- a/src/rateLimiter.ts +++ b/src/rateLimiter.ts @@ -29,19 +29,20 @@ import { RedisStore } from "./redisStore.ts"; export const limit = ( userOptions?: OptionsInterface, ) => { - const options = { ...defaultOptions, ...userOptions }; + const options = { ...defaultOptions, ...(userOptions ?? {}) }; const store = options.storageClient === "MEMORY_STORE" ? 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..1983cae 100644 --- a/src/typesAndDefaults.ts +++ b/src/typesAndDefaults.ts @@ -54,17 +54,24 @@ 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 = { +export const defaultOptions: OptionsInterface = { 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", };