[英]ember data different models for same endpoint
I have an API that doesn't return JSON data in a format that Ember-Data expects. 我有一个API不会以Ember-Data期望的格式返回JSON数据。 Especially when getting a list of resources versus a single resource.
特别是在获取资源列表而不是单个资源时。
For example, GET /api/widgets/{id}
例如,
GET /api/widgets/{id}
Should return a single widget model that might look like this: 应该返回一个看起来像这样的小部件模型:
//app/models/widget.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
weight: DS.attr('number'),
color: DS.attr('string')
});
Whereas getting the full list of widgets via GET /api/widgets/
returns a model that should look like this: 而通过
GET /api/widgets/
小部件的完整列表将返回一个如下所示的模型:
// app/models/widgetlist.js
import DS from 'ember-data';
export default DS.Model.extend({
total: 22,
widgets: DS.hasMany('widget')
});
(I think that's how my widget list model should look. It's essentially a total count of widgets in system and current paginated set of widgets) (我认为这就是我的小部件列表模型的外观。本质上,这是系统中的小部件总数以及当前的分页小部件集)
I'm having a really hard time figuring out what combination of models, custom adapter and/or custom serializer I need in order to get this to work. 我很难确定要使用哪种模型,自定义适配器和/或自定义序列化器组合。
EDIT: 编辑:
// Server responses examples
// GET api/widgets/77
{
"id":77,
"name":"Acoustic Twangdoodle",
"weight":3,
"color":"purple"
}
// GET api/widgets/
{
"total":22,
"widgets":[
{
"id":77,
"name":"Acoustic Twangdoodle",
"weight":3,
"color":"purple"
},
{
"id":88,
"name":"Electric Twangdoodle",
"weight":12,
"color":"salmon"
}
]
}
Thats only one model! 那只是一个模型!
Now I don't see how your pagination works. 现在我看不到您的分页方式。 Depending on that maybe you should not use
findAll
but instead use query
to load a paginated set. 因此,您可能不应该使用
findAll
,而应使用query
来加载分页集。
The total
is not part of the model but of the metadata . total
不是模型的一部分,而是元数据的一部分 。 Use a custom JSONSerializer
and let extractMeta
return this. 使用自定义
JSONSerializer
,让extractMeta
返回此值。
Depending how your pagination works you wanna do something like store.query('widget', { page: 3 })
. 根据分页的工作方式,您想要执行诸如
store.query('widget', { page: 3 })
。 If you speak more about how to access page 2 or so it will be easier to explain this. 如果您更多地谈论如何访问第2页左右,则将更易于解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.