简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM