Raffaeu Raffaeu - 3 months ago 15
Node.js Question

Node.js intercept Promise and elaborate Response

I am getting started with Node.js + Express and at the moment I am writing my HTTP APIs structure.

I have a controller that exposes some methods using the following pattern:
my_controller.js

'use strict';
var AppApiFactory = function (express, appService) {

var api = express.app;

/* Get all apps ordered by Name Ascending */
function getAllApps(request, response) {
appService.getApps(request.query.$expand).then(function (apps) {
response.status(200).send(apps);
})
.catch(function (err) {
console.error('Error occurred in Apps Api: ' + err);
response.status(500).send("" + err);
});
}

/* Routing */
api.get('/api/v1/apps', getAllApps);

return {
getAllApps: getAllApps,
};
};

module.exports = AppApiFactory;


appService is a simple method returned by my ORM which include a Promise and an array of objects.
Now, because I have to implement some ISO/RFC standards, the response has to be translated in a more complex structure like:

{
"data":[my promise array],
"count":10,
"type":"xmlns:mytype..."
}


How can I intercept the Promise returned by the ORM, modify the content and again return another promise from my Express Controller?
Is this possible?

Maybe it's a stupid question but I still didn't master the concept behind promise.
I am coming from .NET/Java, JavaScript(client) worlds so I am a bit new to JavaScript server-side.

Answer

Without knowing more about this specific context, a Promise's .then() statement can be chained, where the "thenable" from one .then() call flows into the next.

In your situation, it might look something like this:

function getAllApps() {
  return appService
    .getApps(request.query.$expand)
    .then(function(apps) {
      response.status(200).send(apps);
      return {
        data: apps,
        count: apps.length,
        type: "xmlns:mytype..."
      }
    })
    .catch(...);
}

Calling getAllApps() would then return a promise, which takes the original response from appService.getApps() and transforms it into the format you're expecting.

getAllApps.then(function(response) {
  console.log(response);
});

// {data: [...], length: 10, type: "..."}

See this MDN article on Promise.prototype.then() for more.