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');
}
export const Buildings = async() => {
const db = await getDB();
return db.collection('buildings');
}
export const Lang = async (language = "en") => {
const db = await getDB(`${config.MONGODB_DB}_${language}`);
return [

View File

@ -1,12 +1,13 @@
import { build, type APIRoute } from "astro";
import validateAccessToken from "../../../lib/utils/validateAccessToken";
import { calculateCurrentAvailableResources, updatePlanetResources } from "../../../lib/utils/resourceManager";
import buildings from '../../../lib/data/buildings.json';
import { getUserByAccessToken, getUserResearch } from "../../../lib/db/users";
import Planet from "../../../types/Planet";
import { createOrUpgradeBuilding, getPlanetById } from "../../../lib/db/planets";
import { ObjectId } from "mongodb";
import DBResource from "../../../types/DBResource";
import { getAllBuildings } from "../../../lib/db/buildings";
import DBBuilding from "../../../types/DBBuilding";
export const POST: APIRoute = async({ request }) => {
const response = await validateAccessToken(request);
@ -36,12 +37,12 @@ export const POST: APIRoute = async({ request }) => {
}
const buildingId = body.building;
let buildingData: {id: string, name: string, requirements: { buildings: Array<{}>, research: Array<{}>, resources: Array<DBResource> }, multiplier: number} | null = null;
buildings.forEach((category: any) => {
// console.log(category.buildings.filter((element: any) => element.id === buildingId)[0]);
if(buildingData !== null) return;
buildingData = category.buildings.find((element: any) => element.id === buildingId);
});
let buildingData: DBBuilding | null = null;
const buildings = await getAllBuildings();
buildingData = buildings.find((element) => element.id === buildingId) ?? null;
if(!buildingData) {
return new Response(
JSON.stringify({
@ -51,7 +52,6 @@ export const POST: APIRoute = async({ request }) => {
}), { 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;
try {
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 BuildingCard from '../../components/BuildingCard.astro';
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 { 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 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 } } = {};
buildingsList.forEach(cat => {
cat.buildings.forEach(building => {
modalSet[building.id] = {
"resources": building.requirements.resources,
"research": building.requirements.research,
"buildings": building.requirements.buildings,
"energy": building.energy
};
});
});
const buildingsByCategory = buildingsList.reduce((acc: { [key: string]: DBBuilding[] }, building) => {
if(!acc[building.category]) acc[building.category] = [];
acc[building.category].push(building);
return acc;
}, {});
---
<Layout title="Buildings">
@ -48,19 +45,18 @@ buildingsList.forEach(cat => {
</div>
</div>
{buildingsList.map(cat => (
<div class="building-card">
{console.log(cat.category)}
<h3>{lang["buildings"][`Label_${cat.category}`]}</h3>
{Object.entries(buildingsByCategory).map(([category, buildings]) => <>
<h1>{getName(lang, 'buildings', `cat-${category}`)}</h1>
<div class="building-cat">
{cat.buildings.map(building => <BuildingCard
{buildings.map(building => (
<BuildingCard
id={building.id}
name={getObj(lang, "buildings", building.id).name}
description={getObj(lang, "buildings", building.id).description ?? ""}
image="/favicon.svg" />)}
</div>
</div>
image="/favicon.svg" />
))}
</div>
</>)}
</Layout>
<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,
}