cb15c5e0d8
Release / Check for new version (push) Has been cancelled
Release / Build macOS ARM64 (push) Has been cancelled
Release / Build macOS x64 (push) Has been cancelled
Release / Build Linux ARM64 (push) Has been cancelled
Release / Build Linux musl ARM64 (push) Has been cancelled
Release / Build Linux musl x64 (push) Has been cancelled
Release / Build Linux x64 (push) Has been cancelled
Release / Build Windows x64 (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
Release / Publish sandbox package to npm (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
CI / Rust (windows-latest - x86_64-pc-windows-msvc) (push) Has been cancelled
CI / Native E2E Tests (push) Has been cancelled
CI / Windows Integration Test (push) Has been cancelled
CI / Global Install (macos-latest) (push) Has been cancelled
CI / Global Install (ubuntu-latest) (push) Has been cancelled
CI / Version Sync Check (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Dashboard (push) Has been cancelled
CI / Sandbox Package (push) Has been cancelled
CI / Rust (macos-latest - aarch64-apple-darwin) (push) Has been cancelled
CI / Rust (macos-latest - x86_64-apple-darwin) (push) Has been cancelled
CI / Global Install (windows-latest) (push) Has been cancelled
54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { Ratelimit } from "@upstash/ratelimit";
|
|
import { Redis } from "@upstash/redis";
|
|
|
|
let _minuteRateLimit: Ratelimit | null = null;
|
|
let _dailyRateLimit: Ratelimit | null = null;
|
|
|
|
function getRedis(): Redis | null {
|
|
const url = process.env.KV_REST_API_URL;
|
|
const token = process.env.KV_REST_API_TOKEN;
|
|
|
|
if (!url || !token) {
|
|
return null;
|
|
}
|
|
|
|
return new Redis({ url, token });
|
|
}
|
|
|
|
const noopRateLimiter = {
|
|
limit: async () => ({ success: true, limit: 0, remaining: 0, reset: 0 }),
|
|
};
|
|
|
|
const MINUTE_LIMIT = Number(process.env.RATE_LIMIT_PER_MINUTE) || 10;
|
|
const DAILY_LIMIT = Number(process.env.RATE_LIMIT_PER_DAY) || 100;
|
|
|
|
export const minuteRateLimit = {
|
|
limit: async (identifier: string) => {
|
|
if (!_minuteRateLimit) {
|
|
const redis = getRedis();
|
|
if (!redis) return noopRateLimiter.limit();
|
|
_minuteRateLimit = new Ratelimit({
|
|
redis,
|
|
limiter: Ratelimit.slidingWindow(MINUTE_LIMIT, "1 m"),
|
|
prefix: "ratelimit:minute",
|
|
});
|
|
}
|
|
return _minuteRateLimit.limit(identifier);
|
|
},
|
|
};
|
|
|
|
export const dailyRateLimit = {
|
|
limit: async (identifier: string) => {
|
|
if (!_dailyRateLimit) {
|
|
const redis = getRedis();
|
|
if (!redis) return noopRateLimiter.limit();
|
|
_dailyRateLimit = new Ratelimit({
|
|
redis,
|
|
limiter: Ratelimit.fixedWindow(DAILY_LIMIT, "1 d"),
|
|
prefix: "ratelimit:daily",
|
|
});
|
|
}
|
|
return _dailyRateLimit.limit(identifier);
|
|
},
|
|
};
|