mirror of
https://github.com/trafficlunar/tomodachi-share.git
synced 2026-03-28 19:23:15 +00:00
fix: connect to redis during runtime, not build
This commit is contained in:
parent
bdab417708
commit
43a70567a4
1 changed files with 18 additions and 9 deletions
|
|
@ -1,13 +1,9 @@
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { createClient } from "redis";
|
import { createClient, RedisClientType } from "redis";
|
||||||
import { auth } from "./auth";
|
import { auth } from "./auth";
|
||||||
|
|
||||||
const client = await createClient({
|
const WINDOW_SIZE = 60;
|
||||||
url: process.env.REDIS_URL,
|
let client: RedisClientType | null = null;
|
||||||
})
|
|
||||||
.on("error", (err) => console.error("Redis client error", err))
|
|
||||||
.connect();
|
|
||||||
const windowSize = 60;
|
|
||||||
|
|
||||||
interface RateLimitData {
|
interface RateLimitData {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -16,6 +12,17 @@ interface RateLimitData {
|
||||||
expires: number;
|
expires: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getRedisClient() {
|
||||||
|
if (!client) {
|
||||||
|
client = createClient({
|
||||||
|
url: process.env.REDIS_URL,
|
||||||
|
});
|
||||||
|
client.on("error", (err) => console.error("Redis client error", err));
|
||||||
|
await client.connect();
|
||||||
|
}
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
// Fixed window implementation
|
// Fixed window implementation
|
||||||
export class RateLimit {
|
export class RateLimit {
|
||||||
private request: NextRequest;
|
private request: NextRequest;
|
||||||
|
|
@ -41,10 +48,12 @@ export class RateLimit {
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const seconds = Math.floor(now / 1000);
|
const seconds = Math.floor(now / 1000);
|
||||||
const currentWindow = Math.floor(seconds / windowSize) * windowSize;
|
const currentWindow = Math.floor(seconds / WINDOW_SIZE) * WINDOW_SIZE;
|
||||||
const expireAt = currentWindow + windowSize;
|
const expireAt = currentWindow + WINDOW_SIZE;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const client = await getRedisClient();
|
||||||
|
|
||||||
// Execute a Redis transaction and get the count
|
// Execute a Redis transaction and get the count
|
||||||
const [result] = await client.multi().incr(key).expireAt(key, expireAt).exec();
|
const [result] = await client.multi().incr(key).expireAt(key, expireAt).exec();
|
||||||
if (!result) {
|
if (!result) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue