am looking for help in redis.get cache on Node.js

Asked

Viewed 71 times

-1

function getCache(key) {
    cache.get(key, (err, value) => {
        if(err){
            return ("err");
        }else{
            return ("" + value);
        }
    });
};

console.log(getCache('fatorial:7'));

I’m trying to get key value saved in redis, but it’s returning Undefined...

I don’t know what else to do... sorry.

The complete code is here:

const express = require("express");
const bodyparser = require("body-parser");
const redis = require("redis");
const fatorialFuncao = require("./fatorial");

const PORT = process.env.PORT || 8080;
const REDIS_PORT = process.env.PORT || 6379;

const cache = redis.createClient(REDIS_PORT);

const app = express();

app.set('view engine', 'ejs');

app.use(express.static('public'));
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json()); 

cache.on("connect", () => {
    console.log("Redis is ready");
});

cache.on("error", (e) => {
    console.log("Redis error", e);
});

function getCache(key) {
    cache.get(key, (err, value) => {
        if(err){
            return ("err");
        }else{
            return ("" + value);
        }
    });
};

console.log(getCache('fatorial:7'));

function setCache(key, value) {
    cache.set(key, value, 'EX', 10000, (err, value) => {
        if(err){
            console.log(err);
        }else{
            console.log("Os parâmetros foram cadastrados no cash com sucesso");
        }
    });
};

app.get("/", (req, res) => {
    res.render('index');
});

app.post("/calculofatorial", (req, res) => {
    let id = req.body.s1;
    let valueId = getCache(`fatorial:${id}`);

    if(valueId){
        res.send(`Obs.: Essa cálculo foi recuperado do cache`);

    }else{
        if(parseInt(parseInt(req.body.s1)) > 0) {
            let calculation = fatorialFuncao(parseInt(req.body.s1))

            setCache(`fatorial:${id}`, calculation);
            res.send(`O fatorial de ${id} é ${calculation}. Obs.: Essa operação não estava armazenada em cache`);

        } else {
            let msgErro = "digite um valor válido"
            res.send(msgErro);
        }
    }
});



app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
});

1 answer

2


This doesn’t make sense:

console.log(getCache('fatorial:7'));

Because the Return inside a callback will not be SYNCHRONOUS, it will probably be asynchronous, and even if it was not asynchronous, yet the return is in a different SCOPE than the getCache function:

function getCache(key) {
    cache.get(key, (err, value) => {
        if(err){
            return ("err");
        }else{
            return ("" + value);
        }
    });
}

There is no Return in getCache that you created, the 2 Returns that exist are not within cache.get and this will never propagate to the getCache scope, first of all read this:

That is console.log will always return Undefined because getCache returns nothing, to work at least you would have to do something like:

function getCache(key, success, error) {
    cache.get(key, (err, value) => {
        if(err){
            if (error) error("err");
        }else{
            if (success) success("" + value);
        }
    });
}

and run like that:

getCache('fatorial:7', (resposta) => {
    console.log(resposta);
});

If you want to catch the mistake:

getCache('fatorial:7', (resposta) => {
    console.log(resposta);
}, (error) => {
    console.error(error);
});

But if I recall Express, as in most, will not recognize the asynchronous within the route to use the res.send and I can’t say with any conviction, but if I’m not mistaken the redis API that you’re using has no support for await, so I would have to do in hand using Promise, thus:

function getCache(key)
{
    return new Promise((resolve, reject) => {
        cache.get(key, (err, value) => {
            if(err){
                reject(err);
            }else{
                resolve("" + value);
            }
        });
    });
}

And use await, thus:

app.post("/calculofatorial", (req, res) => {
    let id = req.body.s1;
    let valueId = await getCache(`fatorial:${id}`);

...
  • fucking... I’m gonna cry.... fucking... friend... I’m really happy... I spent 12 hours trying to understand this... dude... we got it!!!!! thank you... my God... I’m crying from happiness.... Putz. z...

  • god bless you.

  • @Glarcan if solved your problem please mark the answer as correct. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.