Navigate through relationships in JSON response

115 views Asked by At

I have edited my JSON response using this after remote hook.

module.exports = function (server) {
    // Install a `/` route that returns server status
    var router = server.loopback.Router();
    router.get('/', server.loopback.status());

server.use(router);
var remotes = server.remotes();
var modelEnty = server;
//Intercept all responses comming from backend
remotes.after('**', function (ctx, next) {

    var output = ctx.result;
    //if request is comming from Ex /Cutomers,It gives array of objects. 
    if (Object.prototype.toString.call(output) === '[object Array]') {
        var out = { _embedded: { Coffeeshop: [] } };
        output.forEach(function (o) {

            var objOnly = o.toObject();
            var render = {};

            for (var key in objOnly) {
                render[key] = objOnly[key];
                render["_links"] = { self: { href: "http://" + modelEnty.get('host') + ":" + modelEnty.get('port') + modelEnty.get('restApiRoot') + "/" + modelEnty.modelName + "s/" + objOnly.id } };
            }
            out._embedded.Coffeeshop.push(render);
        });
    }
    //if request is comming from Ex /Cutomers/{id},It gives objects. 
    else {
        var out = {};
        var render = {};
        var dataOnly = output.toObject();

        for (var key in dataOnly) {
            render[key] = dataOnly[key];
            render["_links"] = { self: { href: modelEnty.get('protocol')+"://" + modelEnty.get('host') + ":" + modelEnty.get('port') + modelEnty.get('restApiRoot') + "/" + modelEnty.modelName + "s/" + dataOnly.id } };
        }
        out = render;
    }
    ctx.result = out;
    next();
    });

};

This works fine.and gives below result from this URL http://localhost:3000/api/Customers/1

{
   "name": "string",
   "_links": {
      "self": {
          "href": "http://0.0.0.0:3000/api/undefineds/1"
      }
   },
   "city": "string",
   "contact_no": 0,
   "id": 1,
   "coffeeShopId": 1
}

coffeeeShopId is foreign key ID and It refers CoffeeShop Model.I do not need to show "coffeeShopId": 1 in result.I need to show URL to that particular CoffeeShop there.Like this http://localhost:3000/api/Customers/1/CoffeeShops

Solution should be match for every foreign key in result if their are more than one.Is there any solution for this problem? (should dynamically generate http://localhost:3000/api/Customers/1/CoffeeShops this kind of results if there are many relative models)

0

There are 0 answers