host.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import knex from "../../knex";
  2. import * as redis from "../../redis";
  3. import { getRedisKey } from "../../utils";
  4. export const getHost = async (data: Partial<Host>) => {
  5. const getData = {
  6. ...data,
  7. ...(data.address && { address: data.address.toLowerCase() })
  8. };
  9. const redisKey = getRedisKey.host(getData.address);
  10. const cachedHost = await redis.get(redisKey);
  11. if (cachedHost) return JSON.parse(cachedHost);
  12. const host = await knex<Host>("hosts")
  13. .where(getData)
  14. .first();
  15. if (host) {
  16. redis.set(redisKey, JSON.stringify(host), "EX", 60 * 60 * 6);
  17. }
  18. return host;
  19. };
  20. export const banHost = async (addressToBan: string, banned_by_id?: number) => {
  21. const address = addressToBan.toLowerCase();
  22. const currentHost = await knex<Host>("hosts")
  23. .where({ address })
  24. .first();
  25. if (currentHost) {
  26. await knex<Host>("hosts")
  27. .where({ address })
  28. .update({
  29. banned: true,
  30. banned_by_id,
  31. updated_at: new Date().toISOString()
  32. });
  33. } else {
  34. await knex<Host>("hosts").insert({ address, banned: true, banned_by_id });
  35. }
  36. if (currentHost) {
  37. redis.del(getRedisKey.host(currentHost.address));
  38. }
  39. return currentHost;
  40. };