UNPKG

@grace-js/grace

Version:

An opinionated API framework

32 lines 1.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rateLimit = void 0; const error_js_1 = require("../errors/error.js"); const rateLimit = (options) => (app) => { const { windowMs, max, message, statusCode } = options; const requests = new Map(); return app.registerBefore(async (request) => { const ip = app.adapter.getRequestIp(request); if (ip == null) { console.error('No IP address found in request, rate limiting is not possible'); return; } if (!requests.has(ip)) { requests.set(ip, []); } const timestamps = requests.get(ip); const now = Date.now(); // Remove timestamps older than the current window while (timestamps.length > 0 && now - timestamps[0] > windowMs) { timestamps.shift(); } if (timestamps.length >= max) { throw new error_js_1.APIError(statusCode ?? 429, { message: message ?? 'Too many requests' }); } timestamps.push(now); }); }; exports.rateLimit = rateLimit; //# sourceMappingURL=rate-limit.js.map