从Loopback获取自定义的JSON响应

我做了一个简单的API使用Loopback.It工作正常,从这个URL给出下面的结果。 HTTP://本地主机:3000 / API /咖啡店

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

比中间件更好,你可以使用远程钩子

使用afterRemote挂钩 修改 ,logging或以其他方式使用远程方法的结果然后将其发送到远程客户端 。 由于执行远程方法后运行的是afterRemote钩子,它可以访问远程方法的结果,但不能修改input参数。

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

使用下面的代码来创buildjson:

 obj_list = [ { 'name': 'Coffee shop 1', 'city': 'City one','id': 1},...] dict_template = { '_embedded': { 'CoffeeShops': [] } } for object in obj_list: shop_dict = { '_links' : { 'self':{}, 'CoffeeShops':{} }} shop_dict['name'] = object['name'] shop_dict['city'] = object['city'] link = 'http://localhost:3000/CoffeeShops/' + str(object['id']) shop_dict['_links']['self']['href'] = link shop_dict['_links']['CoffeeShops']['href'] = link dict_template['_embedded']['CoffeeShops'].append(shop_dict) print dict_template