gpt4 book ai didi

ember.js - 将关系注入(inject) Ember 有效负载

转载 作者:行者123 更新时间:2023-12-02 06:06:37 25 4
gpt4 key购买 nike

我有一个显示和创建帖子评论的组件,该组件有一个用于创建新评论并通过 POST 将它们发送到后端的表单,正常的有效负载是:

{
data: {
attributes: {
created_at: "foo",
autor: "foo",
text: "foo"
},
relationships: {
post: {
data: { type: "posts", id: 1234 },
id: "1234",
type: "loans"
}
},
type: "comment"
}
}

当您需要在另一个 View 中使用组件时出现问题,更重要的是,当模型的名称不同时,比如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'),
    });

最佳答案

好的,我已经想出了修改有效负载的方法,将其发送到后端。
Ember 有序列化器!

按照本指南,我可以将数据修改到有效负载中,删除它,添加它或任何我需要的东西:

https://guides.emberjs.com/release/models/customizing-serializers/

我的情况,首先我需要将关系添加到评论的模型中,在这一行:

`posts_breakdown: DS.belongsTo ('posts_breakdown')`

然后使用 ember-cli 为评论模型生成一个序列化程序:
`ember generate serializer comment`

最后,如果payload包含post_breakdown关系中的数据,则进入序列化器,将其删除并传递给post关系,这样,payload是相同的:
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;
},
});

关于ember.js - 将关系注入(inject) Ember 有效负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com