Last active
October 1, 2021 19:32
-
-
Save soyart/3d4f202685f0c6b103f1fee7340651e7 to your computer and use it in GitHub Desktop.
Redis cache with Express
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 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