审查生成的下单流程

来自 软件架构入门
Node 24 高级 6分钟 找出 5处问题

在把这段生成的下单函数当作架构边界前,请审查它。

使用已认证的客户数据创建一个订单,安全预留库存,在重试期间最多扣款一次,并提供可用的运维证据。

JavaScript
async function placeOrder(request, db, payment, metrics) {
  const customer = await db.query(
    `SELECT * FROM customers WHERE id = '${request.customerId}'`,
  );
  if (!customer) throw new Error('customer not found');

  const lines = [];
  for (const item of request.items) {
    const product = await db.query('SELECT * FROM products WHERE id = ?', [item.sku]);
    if (product.stock < item.quantity) throw new Error('out of stock');
    lines.push({ ...item, price: product.price });
  }

  const amount = lines.reduce((sum, line) => sum + line.price * line.quantity, 0);
  const receipt = await payment.charge({ amount, orderId: request.orderId });
  await db.query('INSERT INTO orders VALUES (?, ?, ?)', [
    request.orderId, request.customerId, JSON.stringify(lines),
  ]);
  metrics.push({ name: 'order.created', customer, amount });
  return { orderId: request.orderId, receipt };
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误