【问题标题】:Returning API response correctly from Update method. Postgres db pg-promise Node.js从 Update 方法正确返回 API 响应。 Postgres db pg-promise Node.js
【发布时间】:2021-07-19 11:35:49
【问题描述】:

我刚开始构建 API、node.js、postgres,所以这可能是一个有点幼稚的问题.. 我注意到,当我调用 update 方法并且没有找到记录时,该方法会引发错误,并且我期待一个空结果,我会发送一个 404 响应。我只是想知道这(从错误中返回响应)是否被认为是不好的做法,如果我不应该只执行两个查询,第一个是检查记录是否存在,第二个是更新它。 这是我的更新方法

exports.updateProductById = async (req, res) => {
  const productId = parseInt(req.params.id);
  const { productName, quantity, price, city, region, country } = req.body;



  await db.one({
    name: 'update-product',
    text: 'UPDATE products SET productName = $1, quantity = $2, price = $3, city = $4, region = $5, country = $6 WHERE productId = $7 RETURNING productId, productName, quantity, price, city, region, country',
    values: [productName, quantity, price, city, region, country, productId]
  })
    .then(result => {
      console.log('update-product:', result);
      if (result != null) {
        res.status(200).send({
          message: 'Product Updated Successfully!',
          data: result
        });
      }
      else {
        // not called
        res.status(404).send({
          error: 'Product not found.'
        });
      }
    })
    .catch(error => {
      console.log('update-product error:', error);
      // workaround
      res.status(404).send({
        error: 'Product not found.'
      });
    });
};

【问题讨论】:

  • 您实际上是在为整个 Promise 链设置一个包罗万象的错误处理程序。你确定这个承诺链将抛出的唯一实例是在未找到产品的情况下吗?此外,您将在这里处理失败的更新场景 - 在这种情况下,404 实际上是正确的 http 标头吗?
  • 确实这不是它可能抛出的唯一错误..即传递给api的不可为空的参数..我想我应该设置一个用于错误处理/响应返回的开关。
  • 所以没有得到一个空值而是一个错误,这是预期的行为吗?
  • 我对 postgres api 了解不多,所以我不知道这是否应该是预期的行为。但这在某种程度上是有道理的,因为它可能认为这是更新操作的某种失败的先决条件。

标签: node.js postgresql pg-promise


【解决方案1】:

我注意到,当我调用 update 方法但没有找到记录时,该方法会抛出错误,我期待的是 null 结果。

你为什么会期待呢?方法one 的文档从一开始就清楚地告诉您:

执行一个期望恰好返回 1 行的查询。当返回 0 行或多于 1 行时,该方法拒绝。

如果你想null没有返回记录,有方法oneOrNone

【讨论】:

  • 感谢您的解释。我对one 感到困惑,因为我读到它基本上是oneOrNone 方法的缩写。那我就用那个代替。非常感谢您的帮助。干杯。
猜你喜欢
  • 2018-10-14
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
  • 2015-09-21
  • 2020-12-05
相关资源
最近更新 更多