1

I'm trying to implement Redis inside my NodeJS API but having issues to do so. What I try is to make Redis for the endpoint which serves all the users as a response. I'm getting this error from my implementationnode_redis:

The GET command contains a invalid argument type of \"undefined\".\nOnly strings, dates and buffers are accepted. Please update your code to use valid argument types.:

I tried in this way from connection to middleware:

import redis from 'redis';
import { redisConfig } from '../config';
import Logger from './logger';

// Redis default port === 6379
const REDIS_PORT = redisConfig.port || 6379;

// Connect to redis
const client = redis.createClient(REDIS_PORT);

// Check connection
client.on('connect', () => {
  Logger.info('Connected to Redis');
});

client.on('error', () => {
  Logger.error('Redis not connected');
});

export default client;

Then using this above in my controller:

import Client from '../loaders/redis';
const UserController = {
  async getAllUsers(req, res, next) {
    try {
      const users = await DB.User.find({});
      if (!users) {
        Logger.error('User was not found');
        return res.status(404).send('Nothing found');
      }
      // Set users to redis
      await Client.setex(users, 3600, users);

      Logger.info('All the users were found');
      return res.status(200).send(users);
    } catch (err) {
      Logger.error(err);
      return next(err);
    }
  },}

The middleware:

import Client from '../loaders/redis';

// Cache middleware
const cache = (req, res, next) => {
  const { users } = res;
  Client.get(users, (error, cachedData) => {
    if (error) throw error;
    if (cachedData != null) {
      res.send(users, cachedData);
    } else {
      next();
    }
  });
};

export default cache;

The route:

import Controller from '../controllers';
import cache from '../middleware/cacheMiddle';

app.get('/users', cache, Controller.UserCtrl.getAllUsers);

I cannot understand how to use it as I want to adopt Redis to bee able to get the users faster and also I don't know if make sense and also how to do it for the post of a user for example.

Jakub
  • 2,367
  • 6
  • 31
  • 82
  • It looks like `users` is an array of values. The redis `get` method only takes individual keys (e.g. one user). If you're trying to scan redis to get a bunch of things back you'll need to use different functions. This other question might help: https://stackoverflow.com/questions/30728973/redis-get-all-keys-values-from-redis-with-prefix – Adam Coster Mar 24 '20 at 23:33
  • I would like to see an example in my codes as I cannot understand how I should I do that, please – Jakub Mar 25 '20 at 00:06

0 Answers0