I am trying to create a custom list according to the route accessed from the root route. I am using express routing parameters to get the name of the list and add some predefined values to the list.
But i want to check first if the specified name (list name) hasn't already been used by another list in the Redis database. I am using the client.exists command to check if the specified key(list name) exists but it doesn't seem to work at all. Here is my code:
app.get("/:customListName", (req, res) => {
const customListName = req.params.customListName;
console.log(customListName);
client.exists(customListName, (err, reply) => {
if (reply === 0) {
console.log("Doesn't exist!");
const multi = client.multi();
const customList = ["Have fun!", "Play Games!", "Watch Movies!"];
customList.forEach((item) => {
multi.rPush(customListName, item);
});
multi.exec();
} else {
console.log("Exists!");
}
});
});
From the code i have logged the accessed route and a message that specifies if a list exists or else but am surprised to see that the route is shown (which is 'home' in this case) but no message is logged as you can see below:
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
home
CodePudding user response:
Node Redis 4.x uses Promises instead of callbacks. My guess is you are using that version and that this is the source of your problem. Try this:
app.get("/:customListName", async (req, res) => {
const customListName = req.params.customListName;
const itExists = await client.exists(customListName);
if (itExists) {
/* do one thing */
} else {
/* do something else */
}
});
Not 100% sure but I think the .exists
command returns a boolean. But regardless, it'll certainly be truthy or falsy and so this code will work either way.