PrismaPostgresAdvanced
Order creation — stock + transaction
cart-checkout: User-এর order — atomic stock।
3টি অংশবাংলা ভাষায়
export async function createOrder(
userId: number,
items: { productId: number; qty: number }[],
) {
const order = await prisma.$transaction(async (tx) => {
const lines = [];
for (const item of items) {
const product = await tx.product.findUnique({
where: { id: item.productId },
});
if (!product || product.qty < item.qty) {
throw new Error("insufficient stock - " + item.productId);
}
await tx.product.update({
where: { id: item.productId },
data: { qty: { decrement: item.qty } },
});
lines.push({
productId: item.productId,
qty: item.qty,
price: product.price,
});
}
const total = lines.reduce(
(sum, l) => sum + Number(l.price) * l.qty,
0,
);
return tx.order.create({
data: {
userId,
total,
items: { create: lines },
},
});
});
return order;
}- এক transaction — কোনো step ব্যর্থ হলে সব rollback
- stock check + decrement atomic-ish (single-user demo)
- concurrency-তে optimistic/row-lock ভাবলে আরো শক্ত
real-world
production-এ batch/efficiency-তে $queryRaw-UPDATE-এর সঙ্গে WHERE (id, qty >= x) — সু-রক্ষা।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।