2022-10-20 14:51:52 +00:00
|
|
|
import fetch from "node-fetch";
|
|
|
|
import WebsiteTypes from "../../../src/consts/LeaderboardType";
|
2022-10-20 17:00:27 +00:00
|
|
|
import RedisUtils from "../../../src/utils/redisUtils";
|
2022-10-20 14:51:52 +00:00
|
|
|
|
2022-10-20 17:00:27 +00:00
|
|
|
const KEY = "BL_MAP_STAR_";
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {Request} req
|
|
|
|
* @param {Response} res
|
|
|
|
* @returns
|
|
|
|
*/
|
2022-10-20 14:51:52 +00:00
|
|
|
export default async function handler(req, res) {
|
|
|
|
const mapHash = req.query.hash.replace("custom_level_", "").toLowerCase();
|
2022-10-20 17:27:43 +00:00
|
|
|
const difficulty = req.query.difficulty.replace(" ", "");
|
2022-10-20 14:51:52 +00:00
|
|
|
const characteristic = req.query.characteristic;
|
|
|
|
|
2022-10-20 17:36:26 +00:00
|
|
|
const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`;
|
|
|
|
const exists = await RedisUtils.exists(key);
|
2022-10-20 17:00:27 +00:00
|
|
|
if (exists) {
|
2022-10-20 17:36:26 +00:00
|
|
|
const data = await RedisUtils.getValue(key);
|
2022-10-20 17:00:27 +00:00
|
|
|
res.setHeader("Cache-Status", "hit");
|
|
|
|
|
|
|
|
return res.status(200).json({
|
2022-10-20 14:51:52 +00:00
|
|
|
status: "OK",
|
2022-10-20 17:00:27 +00:00
|
|
|
stars: Number.parseFloat(data),
|
2022-10-20 17:27:43 +00:00
|
|
|
difficulty: difficulty,
|
2022-10-20 14:51:52 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-10-21 13:51:29 +00:00
|
|
|
const before = Date.now();
|
2022-10-20 14:51:52 +00:00
|
|
|
const data = await fetch(
|
2022-10-21 15:25:30 +00:00
|
|
|
WebsiteTypes.BeatLeader.ApiUrl.MapData.replace("%h", mapHash),
|
2022-10-20 14:51:52 +00:00
|
|
|
{
|
|
|
|
headers: {
|
|
|
|
"X-Requested-With": "BeatSaber Overlay",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
|
|
|
if (data.status === 404) {
|
2022-10-20 17:00:27 +00:00
|
|
|
return res.status(404).json({
|
2022-10-20 14:51:52 +00:00
|
|
|
status: 404,
|
2022-10-20 17:00:27 +00:00
|
|
|
message: "Unknown Map Hash",
|
2022-10-20 14:51:52 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
const json = await data.json();
|
2022-10-21 13:51:29 +00:00
|
|
|
let starCount = undefined;
|
|
|
|
for (const diff of json.difficulties) {
|
|
|
|
if (
|
|
|
|
diff.difficultyName === difficulty &&
|
|
|
|
diff.modeName === characteristic
|
|
|
|
) {
|
|
|
|
starCount = diff.stars;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (starCount === undefined) {
|
|
|
|
return res.status(404).json({
|
|
|
|
status: 404,
|
|
|
|
message: "Unknown Map Hash",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
await RedisUtils.setValue(key, starCount);
|
|
|
|
console.log(
|
|
|
|
`[Cache]: Cached BL Star Count for hash ${mapHash} in ${
|
|
|
|
Date.now() - before
|
|
|
|
}ms`
|
|
|
|
);
|
2022-10-20 17:00:27 +00:00
|
|
|
res.setHeader("Cache-Status", "miss");
|
|
|
|
return res.status(200).json({
|
2022-10-20 14:51:52 +00:00
|
|
|
status: "OK",
|
2022-10-21 13:51:29 +00:00
|
|
|
stars: starCount,
|
2022-10-20 14:51:52 +00:00
|
|
|
});
|
|
|
|
}
|