25 lines
1.2 KiB
JavaScript
25 lines
1.2 KiB
JavaScript
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import Database from "better-sqlite3";
|
|
import {createRateLimiter, createSqliteRateLimitStore} from "../src/middleware/rateLimit.js";
|
|
|
|
test("SQLite rate limit store shares rolling-window hits between limiter instances", () => {
|
|
const db = new Database(":memory:");
|
|
const firstStore = createSqliteRateLimitStore(db);
|
|
const secondStore = createSqliteRateLimitStore(db);
|
|
const options = {windowMs: 1000, max: 2, keyGenerator: () => "account:test", message: "limited", cleanupIntervalMs: 0};
|
|
const first = createRateLimiter({...options, store: firstStore});
|
|
const second = createRateLimiter({...options, store: secondStore});
|
|
const hit = limiter => {
|
|
let allowed = false, status = null;
|
|
limiter({}, {status(value) {status = value; return this;}, json() {}}, () => {allowed = true;});
|
|
return {allowed, status};
|
|
};
|
|
|
|
assert.deepEqual(hit(first), {allowed: true, status: null});
|
|
assert.deepEqual(hit(second), {allowed: true, status: null});
|
|
assert.deepEqual(hit(first), {allowed: false, status: 429});
|
|
assert.equal(firstStore.consume("account:test", Date.now() + 1001, 1000, 2), true);
|
|
first.close(); second.close(); db.close();
|
|
});
|