Search code examples
node.jspostgresqlexpresspg-promise

Calling a Postgres db function in Node API


I am trying to call this Postgres function core.get_age(bigint) in my queries.js

function getAge(req, res, next){
  var customer_id= parseInt(req.params.customer_id);
  db.one('SELECT * FROM core.get_age($1)', customer_id)
    .then(function(data){
      res.status(200)
        .json({
          status: 'success',
          data : data,
          message: "Retrieved Age"
        });
    })
}

Any my routes in index.js

router.get('/api/age/:customer_id', db.getAge);

When i call http://localhost:8080/api/age/10 in POSTMAN i get 404 error.

What is wrong? This is the first instance i am trying to call a Postgres function(). Just trying to retrieve Postgres table with select * from this.this table works but with function I am getting this 404.


Solution

  • Always use .catch with promises! It will point at the problem, like the invalid number of rows returned in your case.

    function getAge(req, res, next) {
      db.func('core.get_age', +req.params.customer_id)
        .then(data => {
          res.status(200)
            .json({
              status: 'success',
              data : data,
              message: "Retrieved Age"
            });
        })
        .catch(error => {
            console.log(error);
            next();
        })
    }