【发布时间】:2019-02-21 11:33:47
【问题描述】:
我想以这种格式规范化数据:
[
{
id: 3,
status: "active",
created: "2017-07-03T15:36:11+02:00",
published: "2017-07-03T15:38:07+02:00",
linkables: [
{
data: {
content: "Text content of the linkable",
id: 200
}
linkable_type: "content",
module_id: 3,
module_type: "case_study"
},
{
data: {
content: "https://foobar.wee/url_of_the_media.png",
id: 205
}
linkable_type: "media",
module_id: 3,
module_type: "case_study"
},
]
},
...
]
变成这样的:
{
entities: {
contents: {
200: {
content: "Text content of the linkable",
id: 200
}
},
media: {
205: {
content: "https://foobar.wee/url_of_the_media.png",
id: 205
}
},
linkables: {
3_case_study_content_200: {
data: 200, // in the contents key
linkable_type: "content",
module_id: 3,
module_type: "case_study"
},
3_case_study_media_205: {
data: 205, // in the media key
linkable_type: "media",
module_id: 3,
module_type: "case_study"
}
},
caseStudies: {
3: {
id: 3,
status: "active",
created: "2017-07-03T15:36:11+02:00",
linkables: ["3_case_study_content_200", "3_case_study_media_205"]
}
}
},
result: [3]
}
由于这个 PR https://github.com/paularmstrong/normalizr/pull/132 添加了一个函数,因此使用 2.x 版本的 normalizr 可以轻松实现这一点,该函数可以用来动态决定在通过父对象中的值进行规范化时使用哪种方案。
但是,在 3.x.x 版本中,这个附加功能没有实现。根据docs,我会说schemaAttribute 可以完成这项工作。
不幸的是,拥有这段代码并没有给我想要的结果......
export const caseStudies = new schema.Entity('caseStudies');
export const media = new schema.Entity('media',);
export const content = new schema.Entity('contents');
export const linkablesSchema = new schema.Entity(
'linkables',
{},
{
idAttribute: (itm) => {
const id = itm.data.id;
return `${itm.module_id}_${itm.module_type}_${itm.linkable_type}_${id}`;
}
}
);
export const linkableSchemaMap = {
content,
media
};
caseStudies.define({
linkables: [linkablesSchema]
});
export const lschema = new schema.Array(linkableSchemaMap, (value, parent) => {
return parent.linkable_type; // this would replace the PR mentioned above?
});
linkablesSchema.define({
data: lschema
});
感谢您的帮助!
【问题讨论】:
标签: javascript schema normalizr