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.