Skip to content

Commit

Permalink
fix: fix error handlnng
Browse files Browse the repository at this point in the history
  • Loading branch information
s99100532 committed Jun 22, 2024
1 parent ccf8611 commit e694fa0
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions repositories/OrderRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default class OrderRepository extends Repository {
const createOrderStmt =
`INSERT INTO orders (user_id, status) values (?, ?)`;
const orderStatus = OrderStatus.CREATED;

const orderCreateResult = await conn.execute(createOrderStmt, [
userId,
orderStatus,
Expand All @@ -53,26 +54,41 @@ export default class OrderRepository extends Repository {
`INSERT INTO order_item (order_id, product_id) values
${orderProducts.map(() => "(?, ?)").join(",")}`;

await conn.execute(
const createItemResult = await conn.execute(
createItemsStmt,
orderProducts
.map((pd) => [orderId, pd.id])
.flat(),
);

if (!createItemResult.affectedRows) {
throw new Error("items create fail");
}

const updateQuantityStmt =
`UPDATE products SET quantity = quantity - 1 where id in
(${orderProducts.map((_) => "?").join(",")})`;

await conn.execute(
const updateQuantityResult = await conn.execute(
updateQuantityStmt,
orderProducts.map((p) => p.id),
);

if (updateQuantityResult.affectedRows != orderProducts.length) {
throw new Error("quantity update fail");
}

const updateBalanceStmt =
`UPDATE users SET balance = balance - ? where id = (?) `;

await conn.execute(updateBalanceStmt, [amount, userId]);
const updateBalanceResult = await conn.execute(updateBalanceStmt, [
amount,
userId,
]);

if (updateBalanceResult.affectedRows != 1) {
throw new Error("balance update fail");
}

return {
id: orderId,
Expand Down

0 comments on commit e694fa0

Please sign in to comment.