Compare commits

..

No commits in common. "6a7644f59faf0424f59711e3428717c3845e6bd7" and "2304ff48a3186eb29fd87e068c3adb1a44f7c039" have entirely different histories.

4 changed files with 20 additions and 102 deletions

View File

@ -77,16 +77,16 @@ export const getUserResearch = async (user: User): Promise<Array<Research>> => {
return research;
}
export const createOrUpgradeResearch = async (userId: ObjectId, research: Research) => {
export const createOrUpgradeResearch = async (username: string, research: Research) => {
const users = await Users();
const result = await users.updateOne(
{ _id: userId, "research.id": research.id },
{ username, "research.id": research.id },
{ $set: { "research.$.level": research.level } }
);
if (result.modifiedCount === 0) {
await users.updateOne({ _id: userId },
await users.updateOne({ username },
{ $push: { research } }
);
}

View File

@ -17,10 +17,6 @@ export const GET: APIRoute = async ({ request }) => {
});
return new Response(
JSON.stringify({
code: 200,
message: "OK",
data: response
})
JSON.stringify(response)
);
}

View File

@ -1,26 +0,0 @@
import { type APIRoute } from "astro";
import validateAccessToken from "../../../lib/utils/validateAccessToken";
import { getUserByAccessToken, getUserResearch } from "../../../lib/db/users";
export const GET: APIRoute = async({ request }) => {
const response = await validateAccessToken(request);
if(response instanceof Response) return response;
const user = await getUserByAccessToken(response);
if(user === null) {
return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized"
}), { status: 401 }
)
}
return new Response(
JSON.stringify({
code: 200,
message: "OK",
data: await getUserResearch(user)
}), { status: 200 }
)
}

View File

@ -1,15 +1,12 @@
import { type APIRoute } from "astro";
import validateAccessToken from "../../../lib/utils/validateAccessToken";
import { getUserResources, updateUserResources } from "../../../lib/utils/resourceManager";
import research from '../../../lib/data/research.json';
import { createOrUpgradeResearch, getUserByAccessToken, getUserResearch } from "../../../lib/db/users";
import { getPlanetById } from "../../../lib/db/planets";
import Planet from "../../../types/Planet";
import { ObjectId } from "mongodb";
import { calculateCurrentAvailableResources, getResourcesFromPlanet, updatePlanetResources } from "../../../lib/utils/resourceManager";
import DBResource from "../../../types/DBResource";
import calculateAvailableResources from "../../../lib/utils/calculateAvailableResources";
import type DBResource from "../../../types/DBResource";
export const POST: APIRoute = async({ request }) => {
// validate access token
const response = await validateAccessToken(request);
if(response instanceof Response) return response;
@ -23,20 +20,8 @@ export const POST: APIRoute = async({ request }) => {
)
}
let body;
try {
body = await request.json()
} catch(e) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
error: "Invalid JSON body"
}), { status: 400 }
)
}
const researchId = body.research;
// check if research id is valid
const researchId = (await request.json()).research;
const researchData = research.filter((element: any) => element.id === researchId)[0];
if(!researchId || !researchData) {
return new Response(
@ -47,38 +32,17 @@ export const POST: APIRoute = async({ request }) => {
}), { status: 400 }
)
}
let userPlanet: Planet | null;
try {
userPlanet = await getPlanetById(new ObjectId(body.planetId));
} catch(e) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
error: "Invalid planet id"
}), { status: 400 }
)
}
if(!userPlanet) {
return new Response(
JSON.stringify({
code: 404,
message: "Not Found",
error: "Planet not found"
}), { status: 404 }
)
}
// check requirements
// buildings
const buildings = userPlanet.buildings;
const buildings = user.buildings;
researchData.requirements.buildings.forEach((buildingReq) => {
if(buildings.filter((building) => building.id === buildingReq.id)[0]?.level ?? 0 < buildingReq.level) {
if(buildings.filter((building) => building.id === buildingReq.id)[0].level < buildingReq.level) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
error: `${buildingReq.id} level ${buildingReq.level} required, found ${buildings.filter((building) => building.id === buildingReq.id)[0]?.level ?? 0}`
error: `${buildingReq.id} level ${buildingReq.level} required`
}), { status: 400 }
)
}
@ -92,54 +56,38 @@ export const POST: APIRoute = async({ request }) => {
JSON.stringify({
code: 400,
message: "Bad Request",
error: `${researchReq.id} level ${researchReq.level} required, found ${playerResearch.filter((research) => research.id === researchReq.id)[0].level}`
error: `${researchReq.id} level ${researchReq.level} required`
}), { status: 400 }
)
}
});
// resources
const resources = await calculateCurrentAvailableResources(userPlanet._id);
if(!resources) {
return new Response(
JSON.stringify({
code: 500,
message: "Internal Server Error",
error: "Failed to get resources"
}), { status: 500 }
)
}
const resources = await getUserResources(user._id);
const playerCurrentResearch = playerResearch.filter((element: any) => element.id === researchId)[0];
const level = playerCurrentResearch ? playerCurrentResearch.level : 0;
const newResources = structuredClone(resources);
const missingResources: Array<{}> = [];
let hasEnoughResources = true;
Object.entries(researchData.requirements.resources).forEach(([key, value]) => {
const res = resources.filter((element: DBResource) => element.name === key)[0];
const cost = playerCurrentResearch ? value * Math.pow(researchData.multiplier, level) : value;
if(res.amount < cost) {
missingResources.push({
name: key,
required: cost,
available: res.amount
});
return;
}
if(res.amount < cost) hasEnoughResources = false;
else newResources.filter((element: DBResource) => element.name === key)[0].amount -= cost;
});
if(missingResources.length > 0) {
if(!hasEnoughResources) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
data: missingResources
error: "Not enough resources"
}), { status: 400 }
)
}
await updatePlanetResources(userPlanet._id, newResources);
await createOrUpgradeResearch(user._id, { id: researchId, level: level + 1 });
await updateUserResources(user._id, newResources);
await createOrUpgradeResearch(user.username, { id: researchId, level: level + 1 });
return new Response(
JSON.stringify({