-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (90 loc) · 2.61 KB
/
index.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const express = require("express");
const cors = require("cors");
const axios = require("axios");
const createRedisClient = require("./redisClient");
const app = express();
app.use(express.json());
app.use(cors());
const redisClient = createRedisClient();
// ! to set data in redis (key is 'photos' in our case)
app.get("/photos", async (req, res) => {
try {
// Check for cached photos
const cachedPhotos = await redisClient.get("photos");
if (cachedPhotos) {
console.log("Cache hit");
res.json(JSON.parse(cachedPhotos));
} else {
console.log("Cache miss");
// Fetch photos from the API
const response = await axios.get(
"https://jsonplaceholder.typicode.com/photos"
);
// Cache the response data
await redisClient.set("photos", JSON.stringify(response.data));
res.json(response.data);
}
} catch (error) {
console.error(error);
res.status(500).send(error.toString());
}
});
// ! to read data from redis (key is 'photos' in our case)
app.get("/read/:key", async (req, res) => {
try {
const { key } = req.params;
const value = await redisClient.get(key);
if (value) {
res.json(JSON.parse(value));
} else {
res.status(404).send("Not Found");
}
} catch (error) {
console.error(error);
res.status(500).send(error.toString());
}
});
// ! to update data in redis (key is 'photos' in our case)
// ? Body
/*
{
"value": {
"albumId": 101111,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
}
}
*/
app.put("/update/:key", async (req, res) => {
try {
const { key } = req.params;
const { value } = req.body;
// Verify that both key and value are provided
if (!key) return res.status(400).send(`Key is ${key}`);
if (!value) return res.status(400).send(`Value is ${value}`);
const exists = await redisClient.exists(key);
if (exists) {
await redisClient.set(key, JSON.stringify(value));
res.send("Updated");
} else {
res.status(404).send("Not Found");
}
} catch (error) {
console.error(error);
res.status(500).send(error.toString());
}
});
// ! to delete data from redis (key is 'photos' in our case)
app.delete("/delete/:key", async (req, res) => {
try {
const { key } = req.params;
await redisClient.del(key);
res.send("Deleted");
} catch (error) {
console.error(error);
res.status(500).send(error.toString());
}
});
app.listen(3000, () => console.log("Server running on port 3000"));