Pristine Kallio Pristine Kallio - 3 months ago 11
Javascript Question

Refactor npm request method code

Currently using npm request, I want to refactor my code to the following:

app.post('/work_order',function (req,res) {
var work_order = req.body.work_order;
var url = soapURI + work_order;
reqMethod(url);
});

app.get('/work_order/:work_order', function (req, res) {
var work_order = req.params.work_order;
var url = soapURI + work_order;
reqMethod(url);
});

function reqMethod (url){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
// console.log(body); // Print the json response
res.send(body);
}
});
}


Problem is that
reqMethod
is now a promise, and
res.send(body)
is part of it. I couldn't simply
return res.send(body)
. I had 2 repetitive pieces of code (every of them is exactly like that of the method) sit in both
.get
and
.post
, so I want to move them out to a common, reusable method.

Questions:


  1. How can I make it work?

  2. Is
    request
    a good npm module? Can you suggest some alternatives and maybe, better ones?



Thank you

Answer

You have 2 options.

Option 1: Pass the result (res) parameter into the reqMethod:

app.post('/work_order',function (req,res) {
  var work_order = req.body.work_order;
  var url = soapURI + work_order;
  reqMethod(url, res);
});

app.get('/work_order/:work_order', function (req, res) {
  var work_order = req.params.work_order;
  var url = soapURI + work_order;
  reqMethod(url, res);
});
function reqMethod (url, res){
  request({
    url: url,
    json: true
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      // console.log(body); // Print the json response
      res.send(body);
    }
    else {
      //send error here
    }
  });
}

Option 2: Add a callback to reqMethod

app.post('/work_order',function (req,res) {
  var work_order = req.body.work_order;
  var url = soapURI + work_order;
  reqMethod(url, function(err, body) {
    res.send(body)
  );
});

app.get('/work_order/:work_order', function (req, res) {
  var work_order = req.params.work_order;
  var url = soapURI + work_order;
  reqMethod(url, function(err, body) {
    res.send(body)
  );
});
function reqMethod (url, cb){
  request({
    url: url,
    json: true
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      // console.log(body); // Print the json response
      cb(null, body);
    }
    else {
      cb(error)
    }
  });
}