fix: use prefix for plugin rate limit redis store

Signed-off-by: Hellgren Heikki <heikki.hellgren@op.fi>
This commit is contained in:
Hellgren Heikki
2025-02-27 15:13:41 +02:00
parent a68bbc54c0
commit eddd61a600
4 changed files with 14 additions and 8 deletions
@@ -34,7 +34,7 @@ export const createRateLimitMiddleware = (options: {
const rateLimitOptions = config.getConfig(configKey);
return rateLimitMiddleware({
store: RateLimitStoreFactory.create(config),
store: RateLimitStoreFactory.create({ config, prefix: pluginId }),
config: rateLimitOptions,
});
};
@@ -265,7 +265,7 @@ export class MiddlewareFactory {
return rateLimitMiddleware({
store: useDefaults
? undefined
: RateLimitStoreFactory.create(this.#config),
: RateLimitStoreFactory.create({ config: this.#config }),
config: rateLimitOptions,
});
}
@@ -45,7 +45,7 @@ describe('CacheRateLimitStoreFactory', () => {
},
},
});
const store = RateLimitStoreFactory.create(config);
const store = RateLimitStoreFactory.create({ config });
expect(store).toBeUndefined();
});
@@ -62,7 +62,7 @@ describe('CacheRateLimitStoreFactory', () => {
},
},
});
const store = RateLimitStoreFactory.create(config);
const store = RateLimitStoreFactory.create({ config });
expect(store).toBeInstanceOf(RedisStore);
});
});
@@ -23,7 +23,11 @@ import { RedisStore } from 'rate-limit-redis';
* @internal
*/
export class RateLimitStoreFactory {
static create(config: Config): Store | undefined {
static create(options: {
config: Config;
prefix?: string;
}): Store | undefined {
const { config, prefix } = options;
const store = config.getOptionalConfig('backend.rateLimit.store');
if (!store) {
return undefined;
@@ -31,18 +35,20 @@ export class RateLimitStoreFactory {
const type = store.getString('type');
switch (type) {
case 'redis':
return this.redis(store);
return this.redis({ store, prefix });
case 'memory':
default:
return undefined;
}
}
private static redis(storeConfig: Config): Store {
const connectionString = storeConfig.getString('connection');
private static redis(options: { store: Config; prefix?: string }): Store {
const { store, prefix } = options;
const connectionString = store.getString('connection');
const KeyvRedis = require('@keyv/redis').default;
const keyv = new KeyvRedis(connectionString);
return new RedisStore({
prefix,
sendCommand: async (...args: string[]) => {
const client = await keyv.getClient();
return client.sendCommand(args);