Skip to content

Instantly share code, notes, and snippets.

@andris9
Created January 8, 2024 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andris9/9e17f52188b100da3348dfd9d826582d to your computer and use it in GitHub Desktop.
Save andris9/9e17f52188b100da3348dfd9d826582d to your computer and use it in GitHub Desktop.
Vaese mehe rate limit 1 tund
'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