-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (49 loc) 路 1.39 KB
/
Copy pathserver.js
File metadata and controls
56 lines (49 loc) 路 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const Redis = require('redis');
const { resolve } = require('path');
const DEFAULT_EXPIRATION = 3600;
/**
* @param empty for local environment
* @param '{url}' give the url of your redis instance
*/
const redisClient = Redis.createClient();
const app = express();
app.use(cors());
app.get('/photos', async (req, res) => {
const albumId = req.query.albumId;
const photos = await getOrSetCache(`photos?albumId=${albumId}`, async () => {
const { data } = await axios.get(
'http://jsonplaceholder.typicode.com/photos',
{
params: { albumId },
}
);
return data;
});
res.json(photos);
});
app.get('/photos/:id', async (req, res) => {
const photo = await getOrSetCache(`photos:${req.params.id}`, async () => {
const { data } = await axios.get(
`http://jsonplaceholder.typicode.com/photos/${req.params.id}`
);
return data;
});
res.json(photo);
});
function getOrSetCache(key, cb) {
return new Promise((resolve, reject) => {
redisClient.get(key, async (error, data) => {
if (error) return reject(error);
if (data != null) return resolve(JSON.parse(data));
const freshData = await cb();
redisClient.SETEX(key, DEFAULT_EXPIRATION, JSON.stringify(freshData));
resolve(freshData);
});
});
}
app.listen(8080, () => {
console.log('Running on -> http://localhost:8080');
});