我有一个用于显示和创建帖子注释的组件,该组件具有用于创建新注释并通过POST将其发送到后端的表单,正常的有效载荷为:
{
data: {
attributes: {
created_at: "foo",
autor: "foo",
text: "foo"
},
relationships: {
post: {
data: { type: "posts", id: 1234 },
id: "1234",
type: "loans"
}
},
type: "comment"
}
}
问题出在需要在另一个视图中使用组件,更重要的是,当模型的名称不同时(例如posts_breakdown),有效负载为:
{ data: {
attributes: {
created_at: "foo",
autor: "foo",
text: "foo"
},
relationships: {
post: {
data: null
}
},
type: "comment"
}
}
很明显,在注释中,没有关系posts_breakdown,这是我尝试使用posts_breakdown: belongsTo (posts_breakdown)
将这种关系添加到模型的第一件事。
问题是,后端无法识别它并且无法对其进行修改。 后端使用关系上的值将评论与帖子相关联(post_id字段进入评论表)
My question
:是否可以通过某种方式“欺骗”后端和/或修改有效负载,因此认为post_breakdown模型已发布?
以下是我如何定义模型的表示:
comment.js:
export default DS.Model.extend ({
author: DS.attr (),
text: DS.attr (),
created_at: DS.attr (),
post: DS.belongsTo ('post'),
posts_breakdown: DS.belongsTo ('posts_breakdown'),
});
posts.js:
export default DS.Model.extend ({
text: DS.attr (),
created_at: DS.attr (),
author: DS.attr (),
comments: DS.hasMany ('comments'),
});
post_breakdown.js
export default DS.Model.extend ({
most_commented_post: DS.attr (),
last_commented_post: DS.attr (),
frequent_users: DS.attr (),
comments: DS.hasMany ('comments'),
});
答案 0 :(得分:2)
好吧,我已经想出了一种修改有效载荷的方法,可以将其发送到后端。 灰烬有序列化器!
按照本指南,我可以将数据修改为有效负载,擦除,添加或其他所需的内容:
https://guides.emberjs.com/release/models/customizing-serializers/
我的情况是,我需要在此行中将关系添加到评论的模型中:
`posts_breakdown: DS.belongsTo ('posts_breakdown')`
然后使用ember-cli生成注释模型的序列化器:
`ember generate serializer comment`
最后,如果有效负载包含数据到post_breakdown关系中,则将其添加到序列化器中,将其删除并将其传递到发布关系中,这样,有效负载就相同了:
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
/*
This two functions, are necesary because Ember Data changes the underscore
between variable names by dashes. In fact, it's a Ember suggestion.
*/
keyForAttribute: function (key) {
return key;
},
keyForRelationship: function (key) {
return key;
},
serialize(snapshot, options) {
let json = this._super(...arguments);
/* This makes possible to store comments when the comments-panel-loan component is used
in loan_breakdown view with post_breakdown model:
*/
if (json.data.relationships.post_breakdown.data) {
json.data.relationships.loan = {
data: {
type: "posts",
id: json.data.relationships.post_breakdown.data.id }
};
delete json.data.relationships.post_breakdown;
}
return json;
},
});