Last active
January 15, 2023 20:10
-
-
Save ljaviertovar/7ef4511551d763a579251424b2ad3ba3 to your computer and use it in GitHub Desktop.
Cache responses from REST requests with Redis
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
const express = require('express') | |
const responseTime = require('response-time') | |
const redis = require('redis') | |
const axios = require('axios') | |
const runApp = async () => { | |
// connect to redis | |
const client = redis.createClient() | |
client.on('error', (err) => console.log('Redis Client Error', err)); | |
await client.connect(); | |
console.log('Redis connected!') | |
const app = express() | |
// add response-time to requests | |
app.use(responseTime()) | |
app.get('/character', async (req, res) => { | |
try { | |
// check if the request is already stored in the cache, if so, return the response | |
const cacheCharacters = await client.get('characters') | |
if (cacheCharacters) { | |
return res.json(JSON.parse(cacheCharacters)) | |
} | |
// makes the request to the API | |
const response = await axios.get('https://rickandmortyapi.com/api/character') | |
/* Another way to save the data is to save it with the name of the requets url, with the property | |
req.originalUrl which would be the same as '/character' | |
await client.set(req.originalUrl, JSON.stringify(response.data)) | |
*/ | |
// save the response in the cache | |
await client.set('characters', JSON.stringify(response.data)) | |
return res.status(200).json(response.data) | |
} catch (err) { | |
return res.status(err.response.status).json({ mmessage: err.mmessage }) | |
} | |
}) | |
app.get('/characters/:id', async (req, res) => { | |
try { | |
const cacheCharacter = await client.get('cacheCharacter' + req.params.id) | |
if (cacheCharacter) { | |
return res.json(JSON.parse(cacheCharacter)) | |
} | |
const response = await axios.get('https://rickandmortyapi.com/api/character/' + req.params.id) | |
await client.set('cacheCharacter' + req.params.id, JSON.stringify(response.data)) | |
return res.json(response.data) | |
} catch (err) { | |
return res.status(err.response.status) | |
.json({ message: err.message }) | |
} | |
}) | |
app.listen(process.env.PORT || 3000, () => { | |
console.log(`server on port 3000`) | |
}) | |
} | |
runApp() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment