-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
61 lines (54 loc) · 1.64 KB
/
server.js
File metadata and controls
61 lines (54 loc) · 1.64 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
57
58
59
60
61
const express = require("express");
const cors = require("cors");
const { promisify } = require("util");
const redis = require("redis");
const app = express();
const port = process.env.PORT || 3000;
const client = redis.createClient(process.env.REDIS_URL);
const getAsync = promisify(client.get).bind(client);
const keysAsync = promisify(client.keys).bind(client);
app.use(cors());
app.get("/", async (req, res) => {
try {
const keys = await keysAsync("*");
return res.json(
Object.assign(
{},
...(await Promise.all(
keys.map((key) => {
return getAsync(key).then((value) => ({ [key]: parseInt(value) }));
})
))
)
);
} catch (err) {
return res.status(500).send("unavailable");
}
});
app.get("/flush", (req, res) => {
return client.flushall((err, val) => {
if (err) return res.status(500).send("internal server error");
return res.json({ status: "success" });
});
});
app.get("/:id", (req, res) => {
return client.get(req.params.id, (err, rep) => {
if (err) return res.status(500).send("unavailable");
return res.json({ reviews: parseInt(rep) });
});
});
app.post("/:id", (req, res) => {
return client.incr(req.params.id, (err, count) => {
if (err) return res.status(500).send("unavailable");
return res.json({ reviews: parseInt(count) });
});
});
app.delete("/:id", (req, res) => {
return client.decr(req.params.id, (err, count) => {
if (err) return res.status(500).send("unavailable");
return res.json({ reviews: parseInt(count) });
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});