express-rate-limit-ioredis-store
Version:
A redis store implementation to be used alongside ioredis for the express-rate-limit middleware
85 lines • 3.31 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const ioredis_1 = __importDefault(require("ioredis"));
const timekeeper_1 = __importDefault(require("timekeeper"));
const src_1 = __importDefault(require("../../src"));
const usleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
describe('The Store works as a unit', () => {
const redisClient = new ioredis_1.default('localhost:6379');
beforeEach(async () => {
await redisClient.flushall();
timekeeper_1.default.freeze(Date.now());
});
afterEach(async () => {
timekeeper_1.default.reset();
});
it('Increments the key correctly', incrementTest(redisClient));
it('Decrements the key correctly', decrementTest(redisClient));
it('Resets the key correctly', resetTest(redisClient));
it('Sets the prefix correctly', prefixTest(redisClient));
});
function incrementTest(client) {
return async () => {
const store = new src_1.default({
globalPrefix: 'test-',
client,
});
store.init({ windowMs: 1200 });
let result = await store.increment('clientA');
const creationDate = Date.now();
result.totalHits.should.be.equal(1);
result.resetTime.getTime().should.be.equal(creationDate + 1200);
timekeeper_1.default.reset();
await usleep(200);
result = await store.increment('clientA');
result.totalHits.should.be.equal(2);
result.resetTime.getTime().should.be.equal(creationDate + 1200);
};
}
function decrementTest(client) {
return async () => {
const store = new src_1.default({
globalPrefix: 'test-',
client,
});
store.init({ windowMs: 1200 });
await store.increment('clientA');
await store.decrement('clientA');
const storeValue = parseInt((await client.get('test-clientA')));
storeValue.should.be.equal(0);
await store.decrement('clientB');
(0, chai_1.expect)(await client.get('test-clientB')).to.be.null;
};
}
function resetTest(client) {
return async () => {
const store = new src_1.default({
globalPrefix: 'test-',
client,
});
store.init({ windowMs: 1500 });
await store.increment('clientA');
let storeValue = parseInt((await client.get('test-clientA')));
storeValue.should.be.equal(1);
await store.resetKey('clientA');
await store.increment('clientA');
storeValue = parseInt((await client.get('test-clientA')));
storeValue.should.be.equal(1);
await store.resetKey('clientB');
(0, chai_1.expect)(await client.get('test-clientB')).to.be.null;
};
}
function prefixTest(client) {
return async () => {
const store = new src_1.default({ client });
store.init({ windowMs: 1500 });
await store.increment('clientA');
const storeValue = parseInt((await client.get('express-rate-limit-store-clientA')));
storeValue.should.be.equal(1);
};
}
//# sourceMappingURL=ExpressRateLimitIORedisStore.test.js.map