Redis Caching with NodeJs

What is Caching?

Setting Up An Express Server:

'use strict';
const Express = require('express')
const Port = process.env.port || 5000;
const App = Express();
// Start the Server
App.listen(Port, ()=>{
console.log(`server running on port ${Port}`)
})

setting up Redis environment:

'use strict';
const Express = require('express')
const Fetch = require('node-fetch') // to fetch the data
const Redis = require('redis')
const Port = process.env.port || 5000;
// set the redis port
const Redis_Port = process.env.port || 6379;
const App = Express();
// redis client
const Client = Redis.createClient(Redis_Port)
// Start the Server
App.listen(Port, ()=>{
console.log(`server running on port ${Port}`)
})

Implementation of the endpoint:

// set setResponseasync function setResponse(username, repos) {
return `${username} has ${repos} Github repos`
}
// Make request github for dataasync function getRepos(req, res, next) {
try{
console.log('Fetching data.....')
const { username } = req.params;
const response = await Fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// set data to redis
Client.setex(username, 3600, repos);
setResponse(username, repos).then((value) => {
res.send(value)
})
} catch(err) {
console.log(err);
res.status(500);
}
}
App.get('/repos/:username', cache, getRepos);

Implementation of cache middleware:

//cache middlewarefunction cache(req, res, next) {
const { username } = req.params;
Client.get(username, (err, data)=> {
if(err) throw err;
if(data !== null) {
setResponse(username, data).then(res).then((result =>{
res.send(result)
})
}else {
next();
}
})
}

first request:

second request:

Conclusion:

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Custom Event with RxJS

Offline Authentication in the Browser: Part 2 — Hooking up UI with the Vue 3 Composition API

How to Create Native Drag and Drop Functionality in JavaScript

Native drag and drop created in JavaScript

React Forms — Class vs. Functional

QA Automation From Zero-to-Hero with CodeceptJS End-to-End Testing

Learn React’s “Render” Prop Pattern By Building A Pop-Up Modal

willFocus event not fired when called in useEffect hook

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pratik Kumar

Pratik Kumar

More from Medium

Project experience with React.js, node.js with koa.js

Getting started with MongoDB with node.js

Generating the JSON Web Token for the Google Play Developer API

React.js | What is React.js? | Why React.js? | React.js features