Aleksandregvrm
Aleksandregvrm

Reputation: 1

Getting "Error: Socket already opened" in render log when i hosted my node/redis app?

This is the code i'm using, when i use this code on my local machine port:5002 it works fine redis connection is established, however on render it throws this error message

this is the first error i'm getting \Error: getaddrinfo ENOTFOUND red-cntvfksf7o1s73e9q23g at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) { errno: -3008, code: 'ENOTFOUND', syscall: 'getaddrinfo', hostname: 'red-cntvfksf7o1s73e9q23g' }

after that i get this error Error: Socket already opened at RedisSocket.connect (/opt/render/project/src/node_modules/@redis/client/dist/lib/client/socket.js:48:19) at Commander.connect (/opt/render/project/src/node_modules/@redis/client/dist/lib/client/index.js:185:70) at mongoose.Query.exec (/opt/render/project/src/utils/cache.js:18:16)

This is the code

const mongoose = require("mongoose");
const redis = require("redis");

const client = redis.createClient({url:process.env.REDIS_URL_EXTERNAL});
const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = function ({ query }) {
  this.useCache = true;
  this.allQueries = query;
  return this;
};

mongoose.Query.prototype.exec = async function () {
  if (!this.useCache) {
    return exec.apply(this, arguments);
  }
  await client.connect();
  const additionalQueries = this.allQueries;
  const hashName = JSON.stringify(additionalQueries.productsType);
  const key = JSON.stringify(additionalQueries);
  const cachedData = await client.hGet(hashName, key);
  if (cachedData) {
    const doc = JSON.parse(cachedData);
    await client.disconnect();
    return Array.isArray(doc)
      ? doc.map((d) => new this.model(d))
      : new this.model(doc);
  }
  const result = await exec.apply(this, arguments);
  await client.hSet(hashName, key, JSON.stringify(result), {
    EX: 300,
    NX: true,
  });
  await client.disconnect();
  return result;
};

const cleanCache = async (key) => {
  await client.connect();
  client.del(JSON.stringify(key));
  await client.disconnect();
};

module.exports = cleanCache;

Upvotes: 0

Views: 93

Answers (0)

Related Questions