Search code examples
node.jspostgresqlpg-promise

Returning API response correctly from Update method. Postgres db pg-promise Node.js


I'm just starting with building APIs, node.js, postgres so this might be a bit of a naive question.. I have noticed that when I call the update method and no record is found the method throws an error, and I was expecting a null result, where I would send a 404 response. I was just wondering if this (returning a response from an error) is considered bad practice and if I shouldn't just perform two queries instead, the 1st to check if record exists and the 2nd to update it. Here's my update method

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.'
      });
    });
};

Solution

  • I have noticed that when I call the update method and no record is found the method throws an error, and I was expecting a null result.

    Why were you expecting that? Documentation for method one tells you clearly right from start:

    Executes a query that expects exactly 1 row to be returned. When 0 or more than 1 rows are returned, the method rejects.

    If you want null when no records returned, there is method oneOrNone.