SpaceNinjaServer/src/controllers/api/purchaseController.ts
1921703654 75ecabcdaf
Some checks failed
Build / build (pull_request) Failing after 1m13s
Fix currency synchronization and add real-time validation
2025-09-03 02:47:37 +08:00

34 lines
1.3 KiB
TypeScript

import type { RequestHandler } from "express";
import { getAccountIdForRequest } from "../../services/loginService.ts";
import type { IPurchaseRequest } from "../../types/purchaseTypes.ts";
import { handlePurchase } from "../../services/purchaseService.ts";
import { getInventory } from "../../services/inventoryService.ts";
import { sendWsBroadcastTo } from "../../services/wsService.ts";
export const purchaseController: RequestHandler = async (req, res) => {
try {
const purchaseRequest = JSON.parse(String(req.body)) as IPurchaseRequest;
const accountId = await getAccountIdForRequest(req);
const inventory = await getInventory(accountId);
const response = await handlePurchase(purchaseRequest, inventory);
await inventory.save();
res.json(response);
sendWsBroadcastTo(accountId, { update_inventory: true });
} catch (error) {
if (error instanceof Error && error.message.includes('Insufficient')) {
res.status(400).json({
error: 'INSUFFICIENT_CURRENCY',
message: error.message
});
} else {
console.error('Purchase failed:', error);
res.status(500).json({
error: 'PURCHASE_FAILED',
message: 'An error occurred during purchase'
});
}
}
};