Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call PostgreSQL function with parameter using node JS?

I am new to PostgreSQL and node JS. I am creating web service using node js . I have created function in PostgreSQL and its execute successfully. Now what I want that I am calling this function through node JS but I am not getting how to send value in parameter. I want to insert two value "task_name" and "task_type" in table through node JS. How can I achieve this ?

PostgreSQL function --

CREATE FUNCTION inserttask(task_name text, task_type text)
  RETURNS void AS
  $BODY$
      BEGIN
        INSERT INTO tasklist(taskname, tasktype)
        VALUES(task_name, task_type);
      END;
  $BODY$
  LANGUAGE 'plpgsql' VOLATILE
  COST 100;

Node js code --

app.param(['task_name', 'task_type'], function (req, res, next, value) {
  console.log('CALLED ONLY ONCE with', value);
  next();
});

app.get('/inserttask/:task_name/:task_type', function (req, res, next) {
    console.log('vivek');
// var task_name=req.query.task_name;
// var task_type=req.query.task_type;
var task_name='vivek';
var tast_type='singh';
db.any('select inserttask(task_name,task_type)')
//db.any('select getFriends()')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          message: 'Insert Task',
          data: data
        });
    })
    .catch(function (err) {
      return next(err);
    });

})
like image 563
Moin Khan Avatar asked May 02 '17 07:05

Moin Khan


1 Answers

According to documents values go as array | value after qry, try:

db.any('select inserttask($1, $2)', ['task_name','task_type'])

Edit by pg-promise author. The best way to do it is via method func:

db.func('inserttask', ['task_name','task_type'])
like image 167
Vao Tsun Avatar answered Oct 18 '22 21:10

Vao Tsun