@olakai/sdk
Version:
This document demonstrates how to use the Olakai SDK with all its features.
38 lines • 1.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRateLimitMiddleware = createRateLimitMiddleware;
/**
* Create a rate limiting middleware
* This middleware limits the number of calls to a function within a specified time window.
* @param options - The options for the middleware
* @returns A middleware function
* @default options - {
* maxCalls: 100, // Maximum number of calls within the time window
* windowMs: 60000, // Time window in milliseconds
* keyGenerator: (args) => args[0], // Function to generate a key for the rate limit
* }
* @throws {Error} if the rate limit is exceeded
*/
function createRateLimitMiddleware(options) {
const { maxCalls, windowMs, keyGenerator = () => "default" } = options;
const callCounts = new Map();
return {
name: "rateLimit",
beforeCall: async (args) => {
const key = keyGenerator(args);
const now = Date.now();
const record = callCounts.get(key);
if (!record || now > record.resetTime) {
callCounts.set(key, { count: 1, resetTime: now + windowMs });
}
else {
record.count++;
if (record.count > maxCalls) {
throw new Error(`Rate limit exceeded: ${maxCalls} calls per ${windowMs}ms`);
}
}
return args;
},
};
}
//# sourceMappingURL=rateLimiter.js.map