PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to export Redis in Nodejs to different routes

 September 05, 2022     javascript, node.js, nosql, redis     No comments   

Issue

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


Solution

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>));


Answered By - Leibale Eidelman
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing