isuruAb
isuruAb

Reputation: 2240

Get a custom JSON response from Loopback

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"
          }
        }
      }
   ]
   }
}

Upvotes: 1

Views: 1214

Answers (1)

Overdrivr
Overdrivr

Reputation: 6576

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();
});

Upvotes: 2

Related Questions