简体   繁体   English

从Loopback获取自定义JSON响应

[英]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. 我使用Loopback制作了一个简单的API,它可以正常工作并从此URL提供以下结果。 http://localhost:3000/api/CoffeeShops HTTP://本地主机:3000 / API /咖啡店

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

I need to change this JSON to this template, By using Loopback middleware. 我需要通过使用回送中间件将此JSON更改为此模板。

{
  "_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 . 在将其发送到远程客户端之前 ,使用afterRemote挂钩 修改 ,记录或以其他方式使用远程方法的结果 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. 因为afterRemote挂钩是在执行远程方法之后运行的,所以它可以访问远程方法的结果,但不能修改输入参数。

The following code inside coffee-shop.js will do the trick coffee-shop.js的以下代码可以解决问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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