Get a custom JSON response from Loopback

1.1k views Asked by At

I made a simple API using Loopback.It works fine and give the result below from this URL. http://localhost:3000/api/CoffeeShops

[
  {
    "name": "Coffee shop 1",
    "city": "City one",
    "id": 1
  }
]

I need to change this JSON to this template, By using Loopback middleware.

{
  "_embedded": {
    "CoffeeShops": [
      {
        "name": "Coffee shop 1",
        "city": "City one",
        "_links": {
          "self": {
            "href": "http://localhost:3000/CoffeeShops/1"
          },
          "CoffeeShop": {
            "href": "http://localhost:3000/CoffeeShops/1"
          }
        }
      }
   ]
   }
}
1

There are 1 answers

0
Overdrivr On BEST ANSWER

Better yet than a middleware, you can use a remote hook

Use afterRemote hooks to modify, log, or otherwise use the results of a remote method before sending it to a remote client. Because an afterRemote hook runs after the remote method is executed, it can access the result of the remote method, but cannot modify the input arguments.

The following code inside coffee-shop.js will do the trick

CoffeeShop.afterRemote('find', function(ctx, output, next) {
  ctx.result = {
    _embedded: {
      CoffeeShops: [{
        name: output.name,
        city: output.city,
        _links: {
          self: {
            href: "http://localhost:3000/CoffeeShops/" + id
          },
          CoffeeShop: {
            href: "http://localhost:3000/CoffeeShops/" + id
          }
        }
      }]
    }
  };
  next();
});