34 lines
1.3 KiB
TypeScript
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'
|
|
});
|
|
}
|
|
}
|
|
};
|