Skip to content

Instantly share code, notes, and snippets.

@soyart
Last active October 1, 2021 19:32
Show Gist options
  • Select an option

  • Save soyart/3d4f202685f0c6b103f1fee7340651e7 to your computer and use it in GitHub Desktop.

Select an option

Save soyart/3d4f202685f0c6b103f1fee7340651e7 to your computer and use it in GitHub Desktop.
Redis cache with Express
const express = require('express');
const axios = require('axios');
const redis = require('redis');
const cors = require('cors');
const PORT = 8000;
const DEFAULT_EXPIRATION = 3600;
const API_URL = "https://jsonplaceholder.typicode.com/photos"
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// Empty arg bc Redis is running on localhost
const redisClient = redis.createClient();
function getOrSetCache(key, callback) {
return new Promise((resolve, reject) => {
// Redis GET
redisClient.get(key, async (err, data) => {
if (err) return reject(err);
if (data != null) return resolve(JSON.parse(data));
const freshData = await callback();
// Redis SETEX
redisClient.setex(key, DEFAULT_EXPIRATION, JSON.stringify(freshData));
return resolve(freshData);
})
})
}
app.get('/photos', async (req, res) => {
const albumId = req.query.albumId
const data = await getOrSetCache(`photos?albumId=${albumId}`, async () => {
const { data } = await axios.get(`${API_URL}`, {
params: { albumId }
});
return data;
});
res.json(data).end()
})
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment