I have this simple backend for my game. I this code I have request which return me json…
- User
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 }
- Assistant
You want to add three new API endpoints that return a JSON array with
mapNumberandcaseNumberfor beginner, competitive, and master levels. Here's how you can do it:Add the following code after your existing routes:
// Endpoint to get beginner maps info app.get("/api/maps/info/beginner", (req, res) => { const beginnerMapsInfo = Object.keys(beginnerMaps).map((mapKey, index) => ({ map: index + 1, // Map number starts from 1 caseNumber: beginnerMaps[mapKey].caseNumber })); return res.json(beginnerMapsInfo); }); // Endpoint to get competitive maps info app.get("/api/maps/info/competitive", (req, res) => { const competitiveMapsInfo = Object.keys(competitiveMaps).map((mapKey, index) => ({ map: index + 1, // Map number starts from 1 caseNumber: competitiveMaps[mapKey].caseNumber })); return res.json(competitiveMapsInfo); }); // Endpoint to get master maps info app.get("/api/maps/info/master", (req, res) => { const masterMapsInfo = Object.keys(masterMaps).map((mapKey, index) => ({ map: index + 1, // Map number starts from 1 caseNumber: masterMaps[mapKey].caseNumber })); return res.json(masterMapsInfo); });Here's what's happening in the code:
Object.keys(beginnerMaps)(and similarly forcompetitiveMapsandmasterMaps) gets an array of keys (e.g., "map1", "map2", etc.) from the respective JSON objects..map((mapKey, index) => { ... })iterates over the array of keys, wheremapKeyis the current key (e.g., "map1") andindexis the zero-based index of the key (e.g., 0 for "map1").- Inside the callback function, we create a new object with
map: index + 1(to make the map number start from 1 instead of 0) andcaseNumber: beginnerMaps[mapKey].caseNumber, which extracts thecaseNumbervalue from the corresponding map object. - The resulting array of objects is then returned as JSON in the response.
Example responses:
GET /api/maps/info/beginner
[ { "map": 1, "caseNumber": 5 }, { "map": 2, "caseNumber": 5 }, { "map": 3, "caseNumber": 6 }, // assuming you have more maps ... ]GET /api/maps/info/competitive
[ { "map": 1, "caseNumber": 7 }, { "map": 2, "caseNumber": 8 }, { "map": 3, "caseNumber": 9 }, ... ]GET /api/maps/info/master
[ { "map": 1, "caseNumber": 10 }, { "map": 2, "caseNumber": 11 }, { "map": 3, "caseNumber": 12 }, ... ]You can test these new endpoints by visiting
http://localhost:3000/api/maps/info/beginner(and similarly for competitive and master) in your browser or using a tool likecurlor Postman. Happy coding!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.