0

Is it possible to connect redis in index.js and export the redisClient within every route?

For example. Currently my current method is this .

file: redis.js

const redis = require('redis');

const redisClient = redis.createClient({
  socket: {
    host: 'redis-12126.c8.us-east-1-4.ec2.cloud.redislabsdont_event_trylol.com',
    port: '12026',
  },
  password: '121ak19',
});

module.exports = {
  redisClient: redisClient,
};


file: someRoute.route.js

const express = require('express');

const { redisClient } = require('../../redis/connect');

const router = express.Router();

router.route('/test').get(async (req, res) => {
  await redisClient.connect();
  redisClient.zAdd('$200', { score: 1, value: 'value' });

  await redisClient.disconnect();
  res.send({});
});


My second method

const mongoose = require('mongoose');
const app = require('./app');

const config = require('./config/config');
const logger = require('./config/logger');
const redis = require('redis');
mongoose.Promise = require('bluebird');

let server;


let redisClient;

(async () => {
  redisClient = redis.createClient({
    socket: {
      host: '',
      port: '',
    },
    password: ',
  });

  redisClient.on('connect', () => {
    console.log('✅  Successfully connected to Redis!');
  });
  redisClient.on('error', (error) => console.error(`Error  : ${error}`));

  await redisClient.connect();
})();




mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => {
  logger.info('Connected to MongoDB');
  server = app.listen(config.port, () => {
    logger.info(`Listening to port ${config.port}`);
  });
});

const exitHandler = () => {
  if (server) {
    server.close(() => {
      logger.info('Server closed');
      process.exit(1);
    });
  } else {
    process.exit(1);
  }
};

const unexpectedErrorHandler = (error) => {
  logger.error(error);
  exitHandler();
};

process.on('uncaughtException', unexpectedErrorHandler);
process.on('unhandledRejection', unexpectedErrorHandler);

process.on('SIGTERM', () => {
  logger.info('SIGTERM received');
  if (server) {
    server.close();
  }
});


module.exports = {
  client: redisClient,
};

The second method. when i attempt to import it returns undefined.

my current method seems to work however i have to call redisClient.connect(); and redisClient.disconnect(); everytime

youllbehaunted
  • 631
  • 1
  • 8
  • 15
  • Duplicate: [Global Variable in app.js accessible in routes?](https://stackoverflow.com/questions/9765215/global-variable-in-app-js-accessible-in-routes) –  Aug 05 '22 at 17:57
  • did you fix your issue other than disconnect and connect everytiem? I run into the similar issue. I cannot use the exported redisClient unless I reinitiate it again. thanks. – b.mira May 02 '23 at 01:57

1 Answers1

1

You should use one client everywhere, just make sure to .connect() before using it and .quit() when you want to close the app (if you need it at all).

`redis.js`
const client = createClient({
  // ...
});

client.on('error', err => console.error('Redis Client Error', err));

module.exports = client;

`route.js`
const { Router } = require('express'),
  router = new Router();

router.route('/test').get(async (req, res) => {
  await redis.zAdd('$200', { score: 1, value: 'value' });
  res.send({});
});


module.exports = router;

`app.js`
const redis =require('./redis'),
  app = require('express')();

app.use(require('./route'));

redis.connect()
  .then(() => app.listen(<port>));
Leibale Eidelman
  • 2,772
  • 1
  • 17
  • 28