如何在不为 Ember 中的模型创建序列化程序的情况下序列化嵌套对象



我知道,如果我想序列化名为post的模型的嵌套注释,我需要在app/serializer/post中创建序列化程序.js 像这样:

import RESTSerializer from 'ember-data/serializers/rest';
import DS from 'ember-data';
export default RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
});

但是,如果我想在应用程序/服务器/应用程序中序列化它怎么办.js ? 我不想为每个模型定义序列化程序。相反,我希望能够解析 normalizeQueryResponse 中的属于或具有多个关系。

normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
console.log(payload);
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true);
},

我希望能够彻底了解有效负载,如果有效负载中的属性被证明是对象,那么请解决该问题。

有谁知道这是否可能?

当然这是可能的,也是序列化程序和模型的工作方式。 但我建议依赖一个模型,而不是在您的情况下指定类型。 让我们以这个例子为例。

您的模特帖子.js

export default DS.Model.extend((
valueA: DS.attr('string'), // converted to string
valueB: DS.attr('boolean'), // converted to boolean
comments: DS.attr() // not converted and set as it came in the payload
));

您的序列化程序帖子.js

export default RESTSerializer.extend({
// assuming your payload comes in the format of 
// { data: [ {id: 0, valueA: '', valueB: true, comments: [...]}, {id:1 ...} ]
normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
payload.data = payload.data.map((item, index) => ({ // item = {event_type: '', values: ['','']}
id: index, // ONLY if your payload doesnt already have an id
type: 'post', // set the model type
attributes: { // attributes are the values declared in the model
valyeA: item.valueA,
valueB:  item.valueB,
comments: item.comments.map( item => {
// remap your comments to whatever format you need
})
}
}));
return payload;
});

在您的应用程序中的用法

this.get('store').query('post', {...query object...} ).then( 
response => {
let firstItemLoadedComments = response.get('firstObject.values');
// blast comments!
},
error => {
Ember.Logger.error(`cannot load model: ${error}`);
})
.finally(() => {
// set loading to false or something else
});

相关内容

最新更新