UNPKG

@onurege3467/zerohelper

Version:

ZeroHelper is a versatile high-performance utility library and database framework for Node.js, fully written in TypeScript.

47 lines (46 loc) 1.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkRateLimit = checkRateLimit; const localStore = new Map(); /** * Advanced Rate Limiter for API protection. * Returns true if allowed, false if rate limited. */ async function checkRateLimit(key, options) { const { limit, window, storage = 'memory', redisClient } = options; const now = Date.now(); if (storage === 'redis' && redisClient) { const redisKey = `rate_limit:${key}`; const multi = redisClient.multi(); multi.incr(redisKey); multi.ttl(redisKey); const [count, ttl] = await multi.exec(); if (count === 1) { await redisClient.expire(redisKey, window); } const isAllowed = count <= limit; return { allowed: isAllowed, remaining: Math.max(0, limit - Number(count)), reset: ttl > 0 ? now + (ttl * 1000) : now + (window * 1000) }; } else { // Memory Storage let data = localStore.get(key); if (!data || now > data.resetTime) { data = { count: 0, resetTime: now + (window * 1000) }; } data.count++; localStore.set(key, data); const isAllowed = data.count <= limit; return { allowed: isAllowed, remaining: Math.max(0, limit - data.count), reset: data.resetTime }; } }