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 { createClient } from "redis";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { auth } from "./auth";
|
||||
|
||||
const client = await createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
})
|
||||
.on("error", (err) => console.error("Redis client error", err))
|
||||
.connect();
|
||||
const windowSize = 60;
|
||||
const WINDOW_SIZE = 60;
|
||||
let client: RedisClientType | null = null;
|
||||
|
||||
interface RateLimitData {
|
||||
success: boolean;
|
||||
|
|
@ -16,6 +12,17 @@ interface RateLimitData {
|
|||
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
|
||||
export class RateLimit {
|
||||
private request: NextRequest;
|
||||
|
|
@ -41,10 +48,12 @@ export class RateLimit {
|
|||
|
||||
const now = Date.now();
|
||||
const seconds = Math.floor(now / 1000);
|
||||
const currentWindow = Math.floor(seconds / windowSize) * windowSize;
|
||||
const expireAt = currentWindow + windowSize;
|
||||
const currentWindow = Math.floor(seconds / WINDOW_SIZE) * WINDOW_SIZE;
|
||||
const expireAt = currentWindow + WINDOW_SIZE;
|
||||
|
||||
try {
|
||||
const client = await getRedisClient();
|
||||
|
||||
// Execute a Redis transaction and get the count
|
||||
const [result] = await client.multi().incr(key).expireAt(key, expireAt).exec();
|
||||
if (!result) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue