host.queries.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const redis = require("../redis");
  2. const knex = require("../knex");
  3. async function find(match) {
  4. if (match.address) {
  5. const cachedHost = await redis.client.get(redis.key.host(match.address));
  6. if (cachedHost) return JSON.parse(cachedHost);
  7. }
  8. const host = await knex("hosts")
  9. .where(match)
  10. .first();
  11. if (host) {
  12. redisClient.set(
  13. redis.key.host(host.address),
  14. JSON.stringify(host),
  15. "EX",
  16. 60 * 60 * 6
  17. );
  18. }
  19. return host;
  20. }
  21. async function add(params) {
  22. params.address = params.address.toLowerCase();
  23. const existingHost = await knex("hosts")
  24. .where("address", params.address)
  25. .first();
  26. let id = existingHost?.id;
  27. const newHost = {
  28. address: params.address,
  29. banned: !!params.banned,
  30. banned_by_id: params.banned_by_id,
  31. };
  32. if (id) {
  33. await knex("hosts")
  34. .where("id", id)
  35. .update({
  36. ...newHost,
  37. updated_at: params.updated_at || new Date().toISOString()
  38. });
  39. } else {
  40. // Mysql and sqlite don't support returning but return the inserted id by default
  41. [id] = await knex("hosts")
  42. .insert(newHost)
  43. .returning('*');
  44. }
  45. // Query domain instead of using returning as sqlite and mysql don't support it
  46. const host = await knex("hosts")
  47. .where("id", id);
  48. redis.remove.host(host);
  49. return host;
  50. }
  51. module.exports = {
  52. add,
  53. find,
  54. }