我使用Loopback创建了一个简单的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"
}
}
}
]
}
}
答案 0 :(得分:2)
比中间件更好,您可以使用remote hook
使用 afterRemote hooks 来修改,记录或以其他方式使用远程方法的结果,然后再将其发送到远程客户端即可。因为afterRemote挂钩在执行远程方法后运行,所以它可以访问远程方法的结果,但不能修改输入参数。
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();
});