Created
January 8, 2024 13:53
-
-
Save andris9/9e17f52188b100da3348dfd9d826582d to your computer and use it in GitHub Desktop.
Vaese mehe rate limit 1 tund
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
'use strict'; | |
const Redis = require('ioredis'); | |
const redis = new Redis({ | |
port: 6379, | |
host: '127.0.0.1' | |
}); | |
async function rateLimitedIp(ip) { | |
const rlKey = 'ratelimits'; | |
const nextHour = new Date(new Date(Date.now() + 3600 * 1000).toISOString().substring(0, 14) + '00:00.000Z').getTime(); | |
const [[errAdd, resAdd], [errExpire, resExpire]] = await redis.multi().sadd(rlKey, ip).pexpireat(rlKey, nextHour).exec(); | |
if (errAdd || errExpire) { | |
throw errAdd || errExpire; | |
} | |
return !resAdd; | |
} | |
async function main() { | |
if (await rateLimitedIp('1.2.3.4')) { | |
console.log('Rate limited'); | |
return; | |
} | |
console.log('Success'); | |
} | |
main().finally(() => redis.quit()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment