SPB Git

Repository Public

ratelimit.ts 567 B 12 lines typescript

1import { sql } from "./db";23/** Fixed-window counter in PostgreSQL. Returns true while the caller is within the limit. */4export async function rateLimit(key: string, limit: number, windowSeconds: number): Promise<boolean> {5  const [r] = await sql<{ count: number }[]>`6    INSERT INTO rate_limits (key, window_start, count)7    VALUES (${key}, to_timestamp(floor(extract(epoch FROM now()) / ${windowSeconds}) * ${windowSeconds}), 1)8    ON CONFLICT (key, window_start) DO UPDATE SET count = rate_limits.count + 19    RETURNING count`;10  return r.count <= limit;11}12
Files main
Menu

Theme