-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
104eab1
commit 7e1ca98
Showing
5 changed files
with
61 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import Redis from 'ioredis'; | ||
|
||
const redis = new Redis(process.env.REDIS_URL!); | ||
|
||
redis.on('connect', () => { | ||
console.log('Connected to Redis'); | ||
}); | ||
|
||
redis.on('error', (error) => { | ||
console.error('Redis error:', error); | ||
}); | ||
|
||
export async function isRequestAllowed(userId: string,timeWindow:number): Promise<boolean> { | ||
const currentTime = Math.floor(Date.now() / 1000); | ||
const key = `rate_limit:${userId}`; | ||
|
||
const maxRequests = 2; | ||
|
||
const timestamps = await redis.lrange(key, 0, -1); | ||
const validTimestamps = timestamps | ||
.map(Number) | ||
.filter(timestamp => timestamp > currentTime - timeWindow); | ||
|
||
if (validTimestamps.length < maxRequests) { | ||
await redis.multi() | ||
.rpush(key, currentTime) | ||
.expire(key, timeWindow) | ||
.exec(); | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters