Created
December 31, 2021 07:30
-
-
Save devAgam/fb3ad6d733fad0b06875861ff1354778 to your computer and use it in GitHub Desktop.
Sample of Redis cached route in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.get("/sileo-depiction/:package", async (req, res) => { | |
const dep_package = req.params.package; // package name | |
try { | |
const redisDepKey = `${dep_package}:depiction`; // redis key | |
return client.get(redisDepKey, async (err, cachedData) => { // check if cached | |
if (cachedData) { // if cached | |
const parsedData = JSON.parse(depiction); // parse cached data | |
res.status(200).send({ // send cached data | |
httpStatus: 200, | |
success: true, | |
success_binary: 1, | |
data: parsedData, | |
message: "Successfully retrieved data from cache", | |
meta_data: { | |
time_epoch = Math.floor(Date.now() / 1000), | |
time_iso = new Date().toISOString(), | |
} | |
}); | |
} else { // if not cached | |
const firestoreQueryNonce = await firebaseService.getRelease(dep_package); // get fresh data from firestore or other persistent database | |
client.setex(redisDepKey, 259200, JSON.stringify(firestoreQueryNonce)); // cache data for 3 days || redis always store data in string format | |
res.status(200).send({ // send fresh data | |
httpStatus: 200, | |
success: true, | |
success_binary: 1, | |
data: firestoreQueryNonce, | |
message: "Successfully retrieved data from database", | |
meta_data: { | |
time_epoch = Math.floor(Date.now() / 1000), | |
time_iso = new Date().toISOString(), | |
} | |
}); | |
} | |
}); | |
} catch (error) { // if error | |
console.log(error); | |
res.status(500).send({ // send error acknowledgement | |
httpStatus: 500, | |
success: false, | |
success_binary: 0, | |
data: null, | |
message: "could not get data", | |
meta_data: { | |
time_epoch = Math.floor(Date.now() / 1000), | |
time_iso = new Date().toISOString(), | |
} | |
}) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment