SpaceNinjaServer/src/controllers/api/startRecipeController.ts

54 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-05-28 13:45:06 +02:00
import { getAccountIdForRequest } from "@/src/services/loginService";
2024-01-25 14:49:45 +01:00
import { getJSONfromString } from "@/src/helpers/stringHelpers";
import { logger } from "@/src/utils/logger";
import { RequestHandler } from "express";
2024-12-31 01:36:28 +01:00
import { getRecipe } from "@/src/services/itemDataService";
import { addMiscItems, getInventory, updateCurrency } from "@/src/services/inventoryService";
import { unixTimesInMs } from "@/src/constants/timeConstants";
import { Types } from "mongoose";
2024-01-25 14:49:45 +01:00
interface IStartRecipeRequest {
RecipeName: string;
Ids: string[];
}
export const startRecipeController: RequestHandler = async (req, res) => {
const startRecipeRequest = getJSONfromString(String(req.body)) as IStartRecipeRequest;
2024-01-25 14:49:45 +01:00
logger.debug("StartRecipe Request", { startRecipeRequest });
2024-05-28 13:45:06 +02:00
const accountId = await getAccountIdForRequest(req);
2024-01-25 14:49:45 +01:00
2024-12-31 01:36:28 +01:00
const recipeName = startRecipeRequest.RecipeName;
const recipe = getRecipe(recipeName);
if (!recipe) {
logger.error(`unknown recipe ${recipeName}`);
throw new Error(`unknown recipe ${recipeName}`);
}
await updateCurrency(recipe.buildPrice, false, accountId);
const ingredientsInverse = recipe.ingredients.map(component => ({
ItemType: component.ItemType,
ItemCount: component.ItemCount * -1
}));
const inventory = await getInventory(accountId);
addMiscItems(inventory, ingredientsInverse);
//buildtime is in seconds
const completionDate = new Date(Date.now() + recipe.buildTime * unixTimesInMs.second);
inventory.PendingRecipes.push({
ItemType: recipeName,
CompletionDate: completionDate,
_id: new Types.ObjectId()
});
const newInventory = await inventory.save();
res.json({
RecipeId: { $oid: newInventory.PendingRecipes[newInventory.PendingRecipes.length - 1]._id.toString() }
});
2024-01-25 14:49:45 +01:00
};