我正在尝试让 Ember Data 的 JSONAPIAdapter 来处理嵌套资源。对于服务器部分,使用 django-rest-framework-json-api。
我的(简化的)ember 模型:
case.js
export default Model.extend({
firstName: attr('string'),
lastName: attr('string'),
comments: hasMany('comment'),
})
comment.js
export default Model.extend({
text: attr('string'),
case: belongsTo('case'),
})
服务器对 /api/v1/cases/4
的响应如下所示:
{
"data": [
{
"type": "cases",
"id": "4",
"attributes": {
"first-name": "Hans",
"last-name": "Peter",
},
"relationships": {
"comments": {
"meta": {
"count": 1
},
"data": [
{
"type": "comments",
"id": "5"
}
],
"links": {
"related": "http://localhost:8000/api/v1/cases/4/comments"
}
}
}
}
]
}
现在,如果我正确理解 Ember 数据和 JSON-API 规范,当我引用评论时,ember 应该请求 /api/v1/cases/4/comments
。相反,它请求 /api/v1/comments/5
,这显然会返回 404
。
我的问题总结:
- 服务器响应是否符合 JSON-API 规范?
- 如何让 ember 尊重嵌套路由?
我使用的是 ember v2.8。
额外问题:我在创建新评论时面临同样的问题 - 如何让 ember 到 POST
到 /case/4/comments
而不是 /评论
?
最佳答案
JSON API 规范不强制执行任何特定的 URL 模式,因此您尝试执行的操作是合规的。然而,我发现使用 Ember Data 使用平面 URL 结构更容易,尽管有一个解决方法。
您需要查看 ember-data-url-templates插件并将一些逻辑添加到模型的适配器中。
使用该插件,您可以使用 app/adapters/comment.js
执行以下操作:
import ApplicationAdapter from './application';
import UrlTemplates from 'ember-data-url-templates';
export default ApplicationAdapter.extend(UrlTemplates, {
namespace: 'api/v1', // You may or may not need this namespace setting:
// I'm a little rusty in this area :)
urlTemplate: '{+host}/case/{caseId}/comments{/id}',
urlSegments: {
contentId: function(type, id, snapshot/*, query */) {
return snapshot.belongsTo('case', { id: true });
}
}
});
除非该插件有其他办法可以解决这个问题,否则我相信这会将您锁定在该 URL 结构中,以便在整个应用程序中进行评论。因此,在决定走这条路之前,一定要权衡利弊。
关于javascript - Ember 数据 JSONAPIAdapter : fetch nested resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40262698/