-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
58 lines (47 loc) · 2.19 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
const app = require("express")();
app.use(require("cors")());
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const cache = new Map();
const EXPIRES = 1000 * 60 * 60;
app.get("/", (_, res) => res.redirect("https://github.com/domi-btnr/ClientModBadges-API"));
app.get("/users/:userId", async (req, res) => {
const { userId } = req.params;
if (!userId) return res.status(400).json({ error: "No user id provided" });
let _data = {};
if (cache.has(userId) && cache.get(userId).expires > Date.now() && cache.get(userId).badges.length) _data = cache.get(userId).badges;
else {
try {
const resp = await axios.get(`https://replugged.dev/api/v1/users/${userId}`, { headers: { "Cache-Control": "no-cache" }, timeout: 5000 });
if (resp.status != 200 || !resp.data?.badges) return;
const body = resp.data.badges;
_data.Replugged = Object.keys(body).filter(key => body[key] === true);
} catch (error) {
console.error(`[ERROR | Replugged] ${error.message}`);
}
if (Object.keys(_data).length) cache.set(userId, { badges: _data, expires: Date.now() + EXPIRES });
}
const filePath = path.join(__dirname, "users", `${userId}.json`);
if (fs.existsSync(filePath)) {
try {
const data = await fs.promises.readFile(filePath, "utf8");
_data = { ..._data, ...JSON.parse(data) };
} catch (error) {
console.error(error);
}
}
return res.json(_data);
});
app.get("/badges/:clientMod/:badge", (req, res) => {
Object.keys(req.params).forEach(key => { req.params[key] = req.params[key].toLowerCase(); });
const { clientMod, badge } = req.params;
if (!fs.existsSync(path.join(__dirname, "badges", clientMod))) return res.status(404).json({ error: "Client mod not found" });
const filePath = path.join(__dirname, "badges", clientMod, `${badge.split(" ")[0]}.png`);
if (fs.existsSync(filePath)) return res.sendFile(filePath);
else return res.status(404).json({ error: "Badge not found" });
});
const port = process.env.PORT || 5050;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});