如何使用loopbackJS以下列格式制作API响应。
{
"meta": {
"limit": 20,
"next": "/api/Questions/?limit=20&offset=20",
"offset": 0,
"previous": null,
"total_count": 215
},
"objects": [...]
}
答案 0 :(得分:0)
您可以重写回复,我使用afterRemote
remote hook来处理回复。
以下是common/models/car.js
让您入门的示例。
module.exports = function(Car) {
// before the static .find methods
Car.afterRemote('**', function(ctx, car, next) {
console.log(ctx.methodString, 'was invoked remotely');
if(ctx.result) {
var result = ctx.result;
ctx.result = {
objects: result,
meta: {
limit: 20,
next: ctx.req.baseUrl,
offset: 0,
previous: '',
}
};
if(Array.isArray(ctx.result.objects)) {
ctx.result.meta.count = ctx.result.objects.length;
}
}
next();
});
};
使用该代码可以获得如下输出:
{"objects":[
{"model":"Nissan","make":"Leaf","year":2013,"id":1},
{"model":"Telsa","make":"S","year":2014,"id":2},
{"model":"Chevrolet","make":"Volt","year":2014,"id":3},
{"model":"Toyota","make":"Prius C","year":2015,"id":4}
],
"meta":{
"limit":20,
"next":"/api/cars",
"offset":0,
"previous":"",
"count":4
}}