Refactor building handler to use database over JSON

This commit is contained in:
Aelita4 2024-08-09 20:09:41 +02:00
parent c74e61716c
commit 1413ab8f83
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
6 changed files with 59 additions and 225 deletions

View File

@ -1,196 +0,0 @@
[
{
"category": "mines",
"buildings": [
{
"id": "iron-mine",
"requirements": {
"buildings": [],
"research": [],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 11,
"multiplier": 2
},
{
"id": "gold-mine",
"requirements": {
"buildings": [],
"research": [],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 11,
"multiplier": 2.5
},
{
"id": "coal-mine",
"requirements": {
"buildings": [],
"research": [],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 11,
"multiplier": 3
}
]
}, {
"category": "utilities",
"buildings": [
{
"id": "research-lab",
"requirements": {
"buildings": [],
"research": [],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 100,
"multiplier": 3
},
{
"id": "research-facility",
"requirements": {
"buildings": [
{
"id": "research-lab",
"level": 3
}
],
"research": [
{
"id": "advanced-technologies",
"level": 2
}
],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 100,
"multiplier": 2
}
]
}, {
"category": "power-plants",
"buildings": [
{
"id": "coal-power-plant",
"requirements": {
"buildings": [],
"research": [],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 100,
"multiplier": 3
},
{
"id": "nuclear-power-plant",
"requirements": {
"buildings": [
{
"id": "coal-power-plant",
"level": 3
}
],
"research": [
{
"id": "nuclear-power",
"level": 2
}
],
"resources": [
{
"name": "iron",
"amount": 1
},
{
"name": "gold",
"amount": 1
},
{
"name": "coal",
"amount": 1
}
]
},
"energy": 100,
"multiplier": 2
}
]
}
]

18
src/lib/db/buildings.ts Normal file
View File

@ -0,0 +1,18 @@
import DBBuilding from '../../types/DBBuilding';
import { Buildings } from '../db/mongodb';
export const getAllBuildings = async () => {
return (await Buildings()).find({}).toArray() as unknown as Array<DBBuilding>;
}
export const getBuildingById = async (id: string) => {
return (await Buildings()).findOne({
id
}) as unknown as DBBuilding;
}
export const getBuildingsByCategory = async (category: string) => {
return (await Buildings()).find({
category
}).toArray() as unknown as Array<DBBuilding>;
}

View File

@ -35,6 +35,11 @@ export const Planets = async () => {
return db.collection('planets'); return db.collection('planets');
} }
export const Buildings = async() => {
const db = await getDB();
return db.collection('buildings');
}
export const Lang = async (language = "en") => { export const Lang = async (language = "en") => {
const db = await getDB(`${config.MONGODB_DB}_${language}`); const db = await getDB(`${config.MONGODB_DB}_${language}`);
return [ return [

View File

@ -1,12 +1,13 @@
import { build, type APIRoute } from "astro"; import { build, type APIRoute } from "astro";
import validateAccessToken from "../../../lib/utils/validateAccessToken"; import validateAccessToken from "../../../lib/utils/validateAccessToken";
import { calculateCurrentAvailableResources, updatePlanetResources } from "../../../lib/utils/resourceManager"; import { calculateCurrentAvailableResources, updatePlanetResources } from "../../../lib/utils/resourceManager";
import buildings from '../../../lib/data/buildings.json';
import { getUserByAccessToken, getUserResearch } from "../../../lib/db/users"; import { getUserByAccessToken, getUserResearch } from "../../../lib/db/users";
import Planet from "../../../types/Planet"; import Planet from "../../../types/Planet";
import { createOrUpgradeBuilding, getPlanetById } from "../../../lib/db/planets"; import { createOrUpgradeBuilding, getPlanetById } from "../../../lib/db/planets";
import { ObjectId } from "mongodb"; import { ObjectId } from "mongodb";
import DBResource from "../../../types/DBResource"; import DBResource from "../../../types/DBResource";
import { getAllBuildings } from "../../../lib/db/buildings";
import DBBuilding from "../../../types/DBBuilding";
export const POST: APIRoute = async({ request }) => { export const POST: APIRoute = async({ request }) => {
const response = await validateAccessToken(request); const response = await validateAccessToken(request);
@ -36,12 +37,12 @@ export const POST: APIRoute = async({ request }) => {
} }
const buildingId = body.building; const buildingId = body.building;
let buildingData: {id: string, name: string, requirements: { buildings: Array<{}>, research: Array<{}>, resources: Array<DBResource> }, multiplier: number} | null = null; let buildingData: DBBuilding | null = null;
buildings.forEach((category: any) => {
// console.log(category.buildings.filter((element: any) => element.id === buildingId)[0]); const buildings = await getAllBuildings();
if(buildingData !== null) return;
buildingData = category.buildings.find((element: any) => element.id === buildingId); buildingData = buildings.find((element) => element.id === buildingId) ?? null;
});
if(!buildingData) { if(!buildingData) {
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
@ -51,7 +52,6 @@ export const POST: APIRoute = async({ request }) => {
}), { status: 400 } }), { status: 400 }
) )
} }
buildingData = buildingData as {id: string, name: string, requirements: { buildings: Array<{}>, research: Array<{}>, resources: Array<DBResource> }, multiplier: number}; // fuck you typescript
let userPlanet: Planet | null; let userPlanet: Planet | null;
try { try {
userPlanet = await getPlanetById(new ObjectId(body.planetId)); userPlanet = await getPlanetById(new ObjectId(body.planetId));

View File

@ -3,10 +3,12 @@ import Layout from '../../layouts/Layout.astro';
import NavBar from '../../components/NavBar.astro'; import NavBar from '../../components/NavBar.astro';
import BuildingCard from '../../components/BuildingCard.astro'; import BuildingCard from '../../components/BuildingCard.astro';
import { getUserByAccessToken } from '../../lib/db/users'; import { getUserByAccessToken } from '../../lib/db/users';
import { getHighestWeightedLanguage, getLocales, getObj } from '../../lib/utils/langDriver'; import { getHighestWeightedLanguage, getLocales, getName, getObj } from '../../lib/utils/langDriver';
import ResourceBar from '../../components/ResourceBar.astro'; import ResourceBar from '../../components/ResourceBar.astro';
import { getAllBuildings } from '../../lib/db/buildings';
import DBBuilding from '../../types/DBBuilding';
const buildingsList = (await import('../../lib/data/buildings.json')).default; const buildingsList = await getAllBuildings();
const loggedToken = Astro.cookies.get('sessionToken')?.value ?? null; const loggedToken = Astro.cookies.get('sessionToken')?.value ?? null;
const username = Astro.cookies.get('username')?.value ?? ""; const username = Astro.cookies.get('username')?.value ?? "";
@ -21,16 +23,11 @@ const lang = await getLocales(locale);
const modalSet: { [key: string]: { resources: Array<any>, research: Array<any>, buildings: Array<any>, energy: number } } = {}; const modalSet: { [key: string]: { resources: Array<any>, research: Array<any>, buildings: Array<any>, energy: number } } = {};
buildingsList.forEach(cat => { const buildingsByCategory = buildingsList.reduce((acc: { [key: string]: DBBuilding[] }, building) => {
cat.buildings.forEach(building => { if(!acc[building.category]) acc[building.category] = [];
modalSet[building.id] = { acc[building.category].push(building);
"resources": building.requirements.resources, return acc;
"research": building.requirements.research, }, {});
"buildings": building.requirements.buildings,
"energy": building.energy
};
});
});
--- ---
<Layout title="Buildings"> <Layout title="Buildings">
@ -48,19 +45,18 @@ buildingsList.forEach(cat => {
</div> </div>
</div> </div>
{buildingsList.map(cat => ( {Object.entries(buildingsByCategory).map(([category, buildings]) => <>
<div class="building-card"> <h1>{getName(lang, 'buildings', `cat-${category}`)}</h1>
{console.log(cat.category)} <div class="building-cat">
<h3>{lang["buildings"][`Label_${cat.category}`]}</h3> {buildings.map(building => (
<div class="building-cat"> <BuildingCard
{cat.buildings.map(building => <BuildingCard
id={building.id} id={building.id}
name={getObj(lang, "buildings", building.id).name} name={getObj(lang, "buildings", building.id).name}
description={getObj(lang, "buildings", building.id).description ?? ""} description={getObj(lang, "buildings", building.id).description ?? ""}
image="/favicon.svg" />)} image="/favicon.svg" />
</div> ))}
</div> </div>
))} </>)}
</Layout> </Layout>
<style> <style>

11
src/types/DBBuilding.ts Normal file
View File

@ -0,0 +1,11 @@
export default interface DBBuilding {
id: string,
category: string,
requirements: {
buildings: Array<{ id: string, level: number }>,
research: Array<{ id: string, level: number }>,
resources: Array<{ name: string, amount: number }>,
},
energy: number,
multiplier: number,
}