I have this simple backend for my game. I this code I have request which return me json with levels.
I need a add 3 request, which will return me JSON array with map number and caseNumber. I need this for beginner, competitive and master.
Here is the code
const express = require("express");
const path = require("path");
const fs = require("fs");
const cron = require("node-cron");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();
const app = express();
app.use(express.static(path.join(__dirname, "public")));
const boardSizes = [5, 6, 7, 8, 9, 10, 11, 12];
const cache = {};
boardSizes.forEach((size) => {
const filePath = path.join(__dirname, "public", ${size}.json);
if (fs.existsSync(filePath)) {
try {
const data = fs.readFileSync(filePath, "utf8");
cache[size] = JSON.parse(data);
} catch {
cache[size] = null;
}
}
});
const beginnerMaps = require("./public/beginner.json");
const competitiveMaps = require("./public/competitive.json");
const masterMaps = require("./public/master.json");
const dailyMaps = require("./public/daily.json");
app.get("/api/maps/tracks/beginner/:mapId", (req, res) => {
const map = beginnerMaps[req.params.mapId];
if (!map) {
return res.status(404).json({ error: "Map not found" });
}
return res.json(map);
});
app.get("/api/maps/tracks/competitive/:mapId", (req, res) => {
const map = competitiveMaps[req.params.mapId];
if (!map) {
return res.status(404).json({ error: "Map not found" });
}
return res.json(map);
});
app.get("/api/maps/tracks/master/:mapId", (req, res) => {
const map = masterMaps[req.params.mapId];
if (!map) {
return res.status(404).json({ error: "Map not found" });
}
return res.json(map);
});
const levelsData = require("./public/levels.json");
app.get("/api/maps/:mapId", (req, res) => {
const map = levelsData[req.params.mapId];
if (!map) {
return res.status(404).json({ error: "Map not found" });
}
return res.json(map);
});
const DAILY_CHALLENGE_FILE = path.join(__dirname, "dailyCounts.json");
let dailyChallengeState = { currentDay: 70, lastUpdate: Date.now() };
if (fs.existsSync(DAILY_CHALLENGE_FILE)) {
try {
dailyChallengeState = JSON.parse(fs.readFileSync(DAILY_CHALLENGE_FILE, "utf8"));
} catch (e) {
console.error("Error reading dailyChallenge.json", e);
}
} else {
fs.writeFileSync(DAILY_CHALLENGE_FILE, JSON.stringify(dailyChallengeState));
}
function updateDailyChallengeState() {
const now = Date.now();
const msInDay = 24 * 60 * 60 * 1000;
const diff = now - dailyChallengeState.lastUpdate;
if (diff >= msInDay) {
const daysPassed = Math.floor(diff / msInDay);
dailyChallengeState.currentDay += daysPassed;
dailyChallengeState.lastUpdate += daysPassed * msInDay;
fs.writeFileSync(DAILY_CHALLENGE_FILE, JSON.stringify(dailyChallengeState));
}
return msInDay - (now - dailyChallengeState.lastUpdate);
}
app.get("/api/maps/daily/current", (req, res) => {
const timeLeftMs = updateDailyChallengeState();
const dailyMapKeys = Object.keys(dailyMaps);
if (dailyMapKeys.length === 0) {
return res.status(404).json({ error: "No daily maps available" });
}
const index = dailyChallengeState.currentDay % dailyMapKeys.length;
const currentMapKey = dailyMapKeys[index];
const currentMap = dailyMaps[currentMapKey];
res.json(currentMap);
});
app.get("/api/maps/daily/info", (req, res) => {
const timeLeftMs = updateDailyChallengeState();
const dailyMapKeys = Object.keys(dailyMaps);
if (dailyMapKeys.length === 0) {
return res.status(404).json({ error: "No daily maps available" });
}
const index = dailyChallengeState.currentDay % dailyMapKeys.length;
const currentMapKey = dailyMapKeys[index];
res.json({
day: dailyChallengeState.currentDay,
mapKey: currentMapKey,
timeLeft: Math.floor(timeLeftMs / 1000)
});
});
app.get("/api/maps/leaderboard/daily", async (req, res) => {
try {
const dailySnapshot = await db.collectionGroup("daily").get();
const statsDocs = dailySnapshot.docs.filter(doc => doc.id === "stats");
const userDocRefs = statsDocs.map(statsDoc => statsDoc.ref.parent.parent);
const userDocs = await db.getAll(...userDocRefs);
const userDataMap = new Map();
userDocs.forEach(userDocSnap => {
if (userDocSnap.exists) {
userDataMap.set(userDocSnap.ref.path, userDocSnap.data());
}
});
const combined = statsDocs.map(statsDoc => {
const userDocRef = statsDoc.ref.parent.parent;
const userData = userDataMap.get(userDocRef.path) || {};
return {
userId: userDocRef.id,
playerName: userData.playerName || "Anonymous",
flag: userData.flag || "default",
total_stars: statsDoc.data().total_stars || 0
};
});
combined.sort((a, b) => b.total_stars - a.total_stars);
const top100 = combined.slice(0, 100);
return res.json(top100);
} catch (error) {
console.error("Error fetching daily leaderboard:", error);
return res.status(500).json({ error: "Internal Server Error" });
}
});
cron.schedule("0 0 * * *", () => {
const timeLeftMs = updateDailyChallengeState();
const message = {
notification: {
title: "New Daily Challenge Available!",
body: "A new daily challenge has just been unlocked. Check it out now!"
},
topic: "dailyChallenge"
};
admin.messaging().send(message)
.then((response) => {
console.log("Successfully sent notification:", response);
})
.catch((error) => {
console.error("Error sending notification:", error);
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT});
});
And here is the example of beginner.json that i have now
{
"map1": {
"name": "random-1738293577586",
"caseNumber": 5,
"colorGrid": [
[
1,
1,
0,
0,
4
],
[
1,
1,
1,
4,
4
],
[
1,
4,
2,
4,
3
],
[
4,
4,
4,
4,
3
],
[
4,
4,
4,
4,
3
]
],
"solutionCount": 1,
"solvingCombination": [
3,
0,
2,
4,
1
]
},
"map2": {
"name": "random-1738293577586",
"caseNumber": 5,
"colorGrid": [
[
1,
0,
1,
3,
3
],
[
1,
1,
1,
2,
3
],
[
1,
1,
1,
2,
3
],
[
4,
1,
1,
2,
3
],
[
4,
4,
2,
2,
3
]
],
"solutionCount": 1,
"solvingCombination": [
1,
4,
2,
0,
3
]
},
I need something like this:
{
map: 1, caseNumber: 5
}