Falcor Router should return the value from external API

134 Views Asked by At

I am new to JavaScript frameworks and currently trying to setup a falcor router calling an external api (for now consider it as an express api app + mango db, hosted at 3000 port).

Now, I am able to use the request package (commented out lines) and successfully call the Express Api app (which returns obj.rating = 4). But I am unable to send this value from the falcor router instead of the hard-coded value "5".

Below is the falcor-router's server.js code:

app.use('/rating.json', falcorExpress.dataSourceRoute(function (req, res) {
  return new Router([
    {
      route: "rating",
      get: function() {
        var obj;
        // request('http://localhost:3000/rating/101', function (error, response, body) {
        //   obj = JSON.parse(body);
        //   console.log('rating:', obj.rating); // obj.rating = 4
        // });
        return {path:["rating"], value:"5"};
      }
    }
  ]);
}));

The below is the code for index.html:

<script>
function showRating() {
  var model = new falcor.Model({source: new falcor.HttpDataSource('http://localhost/rating.json') });
  model.
    get("rating").
    then(function(response) {
      document.getElementById('filmRating').innerText = JSON.stringify(response.json,null, 4);
    });
}
</script>

I also tried to look at the global variable declaration, synchronize http request calls, promises, then statements etc. But nothing seemed to work, clearly I am missing out something here - not sure what.

1

There are 1 best solutions below

1
James Conkling On BEST ANSWER

The router's get handler expects the return value to be a promise or an observable that resolves to a pathValue. To get your request against the db to work, simply return a promise that resolves to a pathValue, e.g.

  return new Router([
    {
      route: "rating",
      get: function() {
        return request('http://localhost:3000/rating/101', function (error, response, body) {
           return { path: ["rating", value: JSON.parse(body).rating };
         });
      }
    }
  ]);