@developers-joyride/rate-limiter
Version:
A flexible rate limiting library with TypeScript support, Express middleware, and NestJS guard/interceptor capabilities
75 lines (74 loc) • 2.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpressRateLimiterMiddleware = void 0;
const rate_limiter_service_1 = require("../services/rate-limiter.service");
class ExpressRateLimiterMiddleware {
constructor(config) {
this.service = new rate_limiter_service_1.RateLimiterService(config);
}
/**
* Check if a request is allowed based on rate limiting rules
*/
async checkLimit(req) {
return await this.service.checkLimit(req);
}
/**
* Express middleware function
*/
middleware() {
return async (req, res, next) => {
try {
const result = await this.service.checkLimit(req);
const config = this.service.getConfig();
if (config.includeHeaders) {
res.set({
"X-RateLimit-Limit": result.limit.toString(),
"X-RateLimit-Remaining": result.remaining.toString(),
"X-RateLimit-Reset": result.resetTime,
"X-RateLimit-Current": result.current.toString(),
});
}
if (!result.allowed) {
res.status(config.statusCode).json({
error: config.errorMessage,
limit: result.limit,
remaining: result.remaining,
resetTime: result.resetTime,
});
return;
}
next();
}
catch (error) {
console.error("Rate limiter middleware error:", error);
// In case of error, allow the request to prevent blocking
next();
}
};
}
/**
* Reset rate limit for a specific key
*/
async resetLimit(key) {
return await this.service.resetLimit(key);
}
/**
* Get current rate limit info for a key
*/
async getLimitInfo(key) {
return await this.service.getLimitInfo(key);
}
/**
* Close the service connection
*/
async close() {
return await this.service.close();
}
/**
* Get the current configuration
*/
getConfig() {
return this.service.getConfig();
}
}
exports.ExpressRateLimiterMiddleware = ExpressRateLimiterMiddleware;