Skip to content

Commit 404f5ba

Browse files
committed
feat: improve cache purging process
1 parent 0cd154e commit 404f5ba

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

packages/frontend/middleware.ts

+11-5
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ const redis = new Redis({
99
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
1010
})
1111

12-
const THREE_DAYS_IN_MS = 3 * 24 * 60 * 60 * 1000
12+
const THIRTY_DAYS_IN_MS = 30 * 24 * 60 * 60 * 1000
13+
const REDIS_DATA_VERSION = '1'
1314

1415
interface RedisResponse {
1516
value: string
1617
timestamp: number
18+
version: string // in case we want to purge all existing data and start fresh
1719
}
1820

1921
async function isIPBlockedInRedis(ip: string, currentTime: number) {
@@ -27,9 +29,13 @@ async function isIPBlockedInRedis(ip: string, currentTime: number) {
2729
let isIPBlocked = false
2830
if (redisData) {
2931
try {
30-
const { value, timestamp } = redisData
31-
// check if entry is valid and is not more than 3 days old
32-
if (value === BLOCKED_IP_VALUE && currentTime - timestamp <= THREE_DAYS_IN_MS) {
32+
const { value, timestamp, version = '' } = redisData
33+
// check if entry is valid, version is correct and data is not more than 30 days old
34+
if (
35+
value === BLOCKED_IP_VALUE &&
36+
version === REDIS_DATA_VERSION &&
37+
currentTime - timestamp <= THIRTY_DAYS_IN_MS
38+
) {
3339
isIPBlocked = true
3440
}
3541
} catch (error) {
@@ -65,7 +71,7 @@ export async function middleware(request: NextRequest) {
6571
const isIPFromVPN = await isVPN(ip)
6672
if (isIPFromVPN) {
6773
try {
68-
await redis.set(ip, { value: BLOCKED_IP_VALUE, timestamp: currentTime })
74+
await redis.set(ip, { value: BLOCKED_IP_VALUE, timestamp: currentTime, version: REDIS_DATA_VERSION })
6975
} catch (error) {
7076
console.error('Failed to set data in Redis:', error)
7177
}

0 commit comments

Comments
 (0)