feat: Introduce GameConfig to centralize constants for leveling, economy, and inventory, adding new transfer and inventory limits.

This commit is contained in:
syntaxbullet
2025-12-13 12:20:30 +01:00
parent 8818d6bb15
commit 5f4efd372f
5 changed files with 68 additions and 29 deletions

View File

@@ -1,8 +1,9 @@
import { inventory, items, users } from "@/db/schema";
import { eq, and, sql } from "drizzle-orm";
import { eq, and, sql, count } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { economyService } from "@/modules/economy/economy.service";
import { GameConfig } from "@/config/game";
export const inventoryService = {
addItem: async (userId: string, itemId: number, quantity: bigint = 1n, tx?: any) => {
@@ -16,9 +17,14 @@ export const inventoryService = {
});
if (existing) {
const newQuantity = (existing.quantity ?? 0n) + quantity;
if (newQuantity > GameConfig.inventory.maxStackSize) {
throw new Error(`Cannot exceed max stack size of ${GameConfig.inventory.maxStackSize}`);
}
const [entry] = await txFn.update(inventory)
.set({
quantity: sql`${inventory.quantity} + ${quantity}`,
quantity: newQuantity,
})
.where(and(
eq(inventory.userId, BigInt(userId)),
@@ -27,6 +33,20 @@ export const inventoryService = {
.returning();
return entry;
} else {
// Check Slot Limit
const [inventoryCount] = await txFn
.select({ count: count() })
.from(inventory)
.where(eq(inventory.userId, BigInt(userId)));
if (inventoryCount.count >= GameConfig.inventory.maxSlots) {
throw new Error(`Inventory full (Max ${GameConfig.inventory.maxSlots} slots)`);
}
if (quantity > GameConfig.inventory.maxStackSize) {
throw new Error(`Cannot exceed max stack size of ${GameConfig.inventory.maxStackSize}`);
}
const [entry] = await txFn.insert(inventory)
.values({
userId: BigInt(userId),
@@ -105,16 +125,9 @@ export const inventoryService = {
// Since we are modifying buyItem, we can just inline the item addition or call addItem if we update it.
// Let's assume we update addItem next. For now, inline the add logic but cleaner.
const existingInv = await txFn.query.inventory.findFirst({
where: and(eq(inventory.userId, BigInt(userId)), eq(inventory.itemId, itemId)),
});
if (existingInv) {
await txFn.update(inventory).set({ quantity: sql`${inventory.quantity} + ${quantity}` })
.where(and(eq(inventory.userId, BigInt(userId)), eq(inventory.itemId, itemId)));
} else {
await txFn.insert(inventory).values({ userId: BigInt(userId), itemId, quantity });
}
// Add Item using inner logic or self-call if we refactor properly.
// Calling addItem directly within the same transaction scope:
await inventoryService.addItem(userId, itemId, quantity, txFn);
return { success: true, item, totalPrice };
};