This repository has been archived on 2023-11-06. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-overlay/pages/api/beatleader/stars.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-10-20 14:51:52 +00:00
import fetch from "node-fetch";
import WebsiteTypes from "../../../src/consts/LeaderboardType";
2022-10-21 16:12:32 +00:00
import { getValue, setValue, valueExists } 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;
const key = `${KEY}${difficulty}-${characteristic}-${mapHash}`;
2022-10-21 16:12:32 +00:00
const exists = await valueExists(key);
2022-10-20 17:00:27 +00:00
if (exists) {
2022-10-21 16:12:32 +00:00
const data = await 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(
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",
});
}
2022-10-21 16:12:32 +00:00
await setValue(key, starCount);
2022-10-21 13:51:29 +00:00
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
});
}