-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
143 lines (122 loc) · 3.58 KB
/
index.ts
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import cors from "cors";
import express, { Response } from "express";
import redis from "redis";
import { promisify } from "util";
import countryList from "./countries.json";
import { Country, LeaderboardResponse } from "./types";
const allCountries = Object.entries(countryList).reduce(
(prev, [id, country]) => {
prev[id] = { ...country, id };
return prev;
},
{} as { [id: string]: Country }
);
const r = redis.createClient({ db: 1 });
r.on("error", err => console.log(`error: ${err}`));
// keep the connection up
setInterval(() => {
console.log("redisClient => Sending Ping...");
r.ping();
}, 60000); // 60 seconds
const getAsync = promisify(r.get).bind(r);
const app = express();
app.use(cors());
const port = 8080 || process.env.PORT;
app.get("/", (_, res) => {
res.send("sup");
});
app.get("/stats", async (req, res) => {
const { query } = req;
const lastUpdate = parseInt((await getAsync("lastupdate")) || "0", 10);
const from =
(typeof query.from === "string" && parseInt(query.from, 10)) || 0;
if (from > 0 && from >= lastUpdate) {
res.statusMessage = "Not modified";
res.status(304).end();
console.log("304");
return;
}
const multi = r
.multi()
.zrevrangebyscore("leaders:co2", "+inf", "1", "withscores", "limit", 0, 10)
.zrevrangebyscore(
"leaders:trees",
"+inf",
"1",
"withscores",
"limit",
0,
10
)
.hgetall("countries:co2")
.hgetall("countries:trees");
Object.keys(allCountries).forEach(id =>
multi.zrangebyscore(`history:netco2:${id}`, from, "+inf", "withscores")
);
multi.exec((_, replies) => {
parseRedisResponse(res, replies, lastUpdate);
});
});
const parseZrange = (response: any[] = [], splitValueAfterColon = false) =>
response.reduce(
(prev, current, i) => {
if (i % 2) {
const a = prev[prev.length - 1];
a.push(current);
} else {
prev.push([
splitValueAfterColon ? (current as string).split(":")[1] : current
]);
}
return prev;
},
[] as Array<[string, string]>
);
const parseRedisResponse = (
res: Response,
replies: any[],
lastUpdate: number
) => {
const [emissions, trees] = [0, 1].map(i => parseZrange(replies[i]));
const [co2ByCountry, treesByCountry] = [replies[2], replies[3]];
const netCO2History: LeaderboardResponse["netCO2History"] = {};
Object.keys(allCountries).forEach((id, i) => {
netCO2History[id] = parseZrange(replies[4 + i], true);
});
const multi = r.multi();
const fetchPlayers: { [address: string]: boolean } = {};
emissions.forEach(([address]: [string]) => {
fetchPlayers[address] = true;
});
trees.forEach(([address]: [string]) => {
fetchPlayers[address] = true;
});
const addressesToFetch = Object.keys(fetchPlayers);
addressesToFetch.forEach(address => multi.hgetall(`player:${address}`));
multi.get("goe");
multi.exec((_, goeAndPlayersFromRedis) => {
const goeMillisCirculating = parseInt(goeAndPlayersFromRedis.pop(), 10);
res.send({
lastUpdate,
goeMillisCirculating,
players: goeAndPlayersFromRedis
.map(p => p || { name: "Mr. Mysterious", countryId: "unknown" })
.reduce(
(prev, current, i) => {
prev[addressesToFetch[i]] = current;
return prev;
},
{} as LeaderboardResponse["players"]
),
emissions,
trees,
netCO2History,
co2ByCountry,
treesByCountry
});
});
};
app.listen(port, () => {
// tslint:disable-next-line:no-console
console.log(`server started at http://localhost:${port}`);
});