UNPKG

@trpc-limiter/redis

Version:

Redis Rate Limiter Adapter for tRPC Limiter.

50 lines (49 loc) 1.18 kB
// src/index.ts import { defineLimiterWithProps } from "@trpc-limiter/core"; import { RateLimiterMemory, RateLimiterRedis, RateLimiterRes } from "rate-limiter-flexible"; export * from "rate-limiter-flexible"; import { defaultFingerPrint } from "@trpc-limiter/core"; var isBlocked = async (store, fingerprint) => { try { await store.consume(fingerprint); return null; } catch (error) { if (error instanceof RateLimiterRes) { return Math.round(error.msBeforeNext / 1e3) || 1; } throw error; } }; var createTrpcRedisLimiter = defineLimiterWithProps( { store: (opts) => { return new RateLimiterRedis({ storeClient: opts.redisClient, keyPrefix: "RATE_LIMIT", points: opts.max, duration: opts.windowMs / 1e3, insuranceLimiter: opts.limiter(opts) }); }, isBlocked }, (currentState) => { return { redisClient: currentState.redisClient, limiter: currentState.limiter ?? (() => new RateLimiterMemory({ points: currentState.max, duration: currentState.windowMs / 1e3 })) }; } ); export { createTrpcRedisLimiter, defaultFingerPrint };