Tuesday, 2 May 2017

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

})



via Moin Khan

No comments:

Post a Comment