Skip to content

Instantly share code, notes, and snippets.

@ditikrushna
Created May 4, 2021 09:01
Show Gist options
  • Save ditikrushna/c43dbb98ffe31d1465859d715123382f to your computer and use it in GitHub Desktop.
Save ditikrushna/c43dbb98ffe31d1465859d715123382f to your computer and use it in GitHub Desktop.
Caching API with Redis and Node
"use strict"
const express = require("express");
const fetch = require("node-fetch");
const redis = require("redis");
const app = express();
const PORT = process.env.PORT || 4000 ;
const PORT_REDIS = process.env.PORT || 6379 ;
const redisClient = redis.createClient(PORT_REDIS);
const set = (key , value) => {
console.log("Redis Set Method occured!")
redisClient.set(key , JSON.stringify(value));
}
const get = (req , res , next) => {
let key = req.route.path ;
console.log("Cache Get Function Occured!");
redisClient.get(key , (error , data) =>{
if(error) res.status(400).send(error);
if(data !== null){
res.status(200).send(JSON.parse(data));
}else{
next();
}
});
}
app.get("/spacex/launches", get ,(req, res) => {
fetch("https://api.spacexdata.com/v3/launches/latest")
.then(res => res.json())
.then(json => {
set(req.route.path , json);
res.status(200).send(json)
})
.catch(error => {
console.error(error);
res.status(400).send(error);
});
});
app.listen(PORT , () => console.log(`Server up and running on ${PORT}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment