ratelimits.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { Database } from "bun:sqlite";
  2. const ratelimitsDB = new Database("./data/ratelimits.sqlite");
  3. export default (type, value, limit, seconds) => {
  4. ratelimitsDB.run(`create table if not exists ${type} (
  5. subject text not null primary key,
  6. countLeft integer default ${limit},
  7. timestamp datetime default current_timestamp
  8. );`)
  9. const statement = ratelimitsDB.prepare(`
  10. INSERT INTO ${type} (subject)
  11. VALUES ($value)
  12. ON CONFLICT(subject) DO UPDATE SET
  13. countLeft = CASE
  14. WHEN (strftime('%s', 'now') - strftime('%s', timestamp)) > $seconds THEN $limit
  15. ELSE MAX(0, countLeft - 1)
  16. END,
  17. timestamp = CASE
  18. WHEN (strftime('%s', 'now') - strftime('%s', timestamp)) > $seconds THEN CURRENT_TIMESTAMP
  19. ELSE timestamp
  20. END
  21. RETURNING countLeft, timestamp;
  22. `);
  23. const result = statement.get({
  24. $value: value,
  25. $seconds: seconds,
  26. $limit: limit
  27. });
  28. if (result.countLeft <= 0) {
  29. const resetTime = new Date(new Date(result.timestamp).getTime() + seconds * 1000);
  30. return { status: true, until: resetTime };
  31. }
  32. return { status: false, countLeft: result.countLeft };
  33. }