我使用REST适配器,当我调用App.Message.find()
Ember.js调用/messages
来检索所有消息,并期望看到这样的JSON结构:
{
"messages": [] // array contains objects
}
然而,API我必须与响应总是使用:
{
"data": [] // array contains objects
}
我只找到了改变API的命名空间或URL的方法。如何告诉REST适配器寻找data
而不是messages
属性?
如果这是不可能的,如何解决这个问题?CTO说我们可以根据需要调整API以与REST适配器一起使用,但由于某种原因,我们无法更改每个响应上的data
属性。
假设您可以编写自己的适配器来处理差异,那么在成功回调中,您可以简单地将传入名称从"data"修改为您的特定实体-在上面的"messages"的情况下
我这样做是为了让你了解在自定义适配器
中可能发生什么在下面的链接中,我突出显示了findMany
的返回行从我的REST api返回的json看起来像[
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
我需要在ember-data让它看起来像这样之前对它进行转换
{
"sessions": [
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
}
https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js L56-57
findMany: function(store, type, ids, parent) {
var json = {}
, adapter = this
, root = this.rootForType(type)
, plural = this.pluralize(root)
, ids = this.serializeIds(ids)
, url = this.buildFindManyUrlWithParent(store, type, ids, parent);
return this.ajax(url, "GET", {
data: {ids: ids}
}).then(function(pre_json) {
json[plural] = pre_json; //change the JSON before ember-data gets it
adapter.didFindMany(store, type, json);
}).then(null, rejectionHandler);
},