Currently, I am in the process of developing an online store for my school's guild organization.
I must admit that I lack experience working with databases and Knex.js is still a bit challenging for me.
An issue arises when multiple users simultaneously add items to their carts - sometimes resulting in more items being added than what is available in the database. It has led me to believe that I might not have fully grasped the concept of transactions and their functionality. Selling excess tickets or products due to this error could potentially put us in a difficult situation. Any guidance on how to handle this scenario better would be greatly appreciated.
The following code snippet exemplifies my attempt at incorporating the transaction:
private async inventoryToCartTransaction(
cart: sql.Cart,
inventoryId: UUID,
quantity: number = 1,
) {
return this.knex.transaction(async (trx) => {
const inventory = await trx<sql.ProductInventory>(TABLE.PRODUCT_INVENTORY)
.where({ id: inventoryId }).first();
if (!inventory) throw new Error(`Inventory with id ${inventoryId} not found`);
if (inventory.quantity < quantity) throw new Error('Not enough inventory');
// More code follows...
});
}
This is how the data is structured within the database:
export interface Product {
id: UUID,
name: string,
description: string,
SKU: string,
price: number,
image_url: string,
max_per_user: number,
category_id: UUID,
created_at: Date,
updated_at: Date,
deleted_at?: Date,
}
// Additional data structure interfaces listed below...