host.queries.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. let { id } = await knex("hosts")
  24. .where("address", params.address)
  25. .first();
  26. const newHost = {
  27. address: params.address,
  28. banned: !!params.banned,
  29. banned_by_id: params.banned_by_id,
  30. };
  31. if (id) {
  32. await knex("hosts")
  33. .where("id", id)
  34. .update({
  35. ...newHost,
  36. updated_at: params.updated_at || new Date().toISOString()
  37. });
  38. } else {
  39. // Mysql and sqlite don't support returning but return the inserted id by default
  40. [id] = await knex("hosts")
  41. .insert(newHost)
  42. .returning('*');
  43. }
  44. // Query domain instead of using returning as sqlite and mysql don't support it
  45. const host = await knex("hosts")
  46. .where("id", id);
  47. redis.remove.host(host);
  48. return host;
  49. }
  50. module.exports = {
  51. add,
  52. find,
  53. }