I would like to have an advice. In my nodeJS/Mongo Stack, One of my Rest API takes time to return since it is doing chains of operation before returning the results. But for some of the operations , I am not concerned about the return status of the same. So my question is, Is it ok for REST API to return the result before completing all operations, instead wait only for major Operation.
My Original code is like this.
router.post('/updateStatus’, validateToken, function(req, res) {
if (req.body.hasOwnProperty(‘param1’) && req.body.hasOwnProperty(‘param2’) ) {
statusCollection.updateStatus(req.body.param1, req.body.param2,function (err, out) {
reportCollection.updateReport(req.body.param1, req.body.param2,function (err, out) {
var result = {status:200, data:out};
res.json(result);
} );
} );
} else {
res.status(422);
res.json({error:'Missing required params'});
}
});
I would like to change as:
router.post('/updateStatus’, validateToken, function(req, res) {
if (req.body.hasOwnProperty(‘param1’) && req.body.hasOwnProperty(‘param2’) ) {
statusCollection.updateStatus(req.body.param1, req.body.param2,function (err, out) {
var result = {status:200, data:out};
res.json(result);
//***************Will continue in After returning API ********************
reportCollection.updateReport(req.body.param1, req.body.param2,function (err, out) {} );
} );
} else {
res.status(422);
res.json({error:'Missing required params'});
}
});
i.e, I will return result after statusCollection.updateStatus() and not waiting till reportCollection.updateReport(). Is this OK?
Some times, you can have heavy operations, in that case you can't always wait before returning the result to the client.
For that reason, you have to think about what is needed for the client and what can be done in background which will not impact the client.
When you find that, you can split the tasks and use jobs or other strategies to delegate the code that must be done in background and reduce the response time.
some times, you can use websocket or pulling to update the client when the heavy operation is done, if the client need the result of that operation to be up to date.
it's a common strategy to separate the computation and does not appear as an error for me.