从 Loopback 获取自定义 JSON 响应
Get a custom JSON response from Loopback
我使用 Loopback.It 做了一个简单的 API,效果很好,下面给出了这个 URL 的结果。
http://localhost:3000/api/CoffeeShops
[
{
"name": "Coffee shop 1",
"city": "City one",
"id": 1
}
]
我需要将此 JSON 更改为此模板,通过使用 Loopback 中间件。
{
"_embedded": {
"CoffeeShops": [
{
"name": "Coffee shop 1",
"city": "City one",
"_links": {
"self": {
"href": "http://localhost:3000/CoffeeShops/1"
},
"CoffeeShop": {
"href": "http://localhost:3000/CoffeeShops/1"
}
}
}
]
}
}
比中间件更好的是,您可以使用 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.
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();
});
我使用 Loopback.It 做了一个简单的 API,效果很好,下面给出了这个 URL 的结果。 http://localhost:3000/api/CoffeeShops
[
{
"name": "Coffee shop 1",
"city": "City one",
"id": 1
}
]
我需要将此 JSON 更改为此模板,通过使用 Loopback 中间件。
{
"_embedded": {
"CoffeeShops": [
{
"name": "Coffee shop 1",
"city": "City one",
"_links": {
"self": {
"href": "http://localhost:3000/CoffeeShops/1"
},
"CoffeeShop": {
"href": "http://localhost:3000/CoffeeShops/1"
}
}
}
]
}
}
比中间件更好的是,您可以使用 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.
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();
});