【问题标题】:denormalise reverse processStrategy反规范化逆向处理策略
【发布时间】:2019-05-11 07:30:16
【问题描述】:

我有一个 API 可以通过 fields 属性中的属性提供这样的数据。

{
records: [
    {
    id: "123",
    fields: {
        author: {
        id: "1",
        name: "Paul"
        },
        title: "My awesome blog post",
        comments: [
        {
            id: "324",
            commenter: {
            id: "2",
            name: "Nicole"
            }
        }
        ]
    }
    }
]
};

在规范化时,我现在使用简单的 processStrategy: (input, parent, key) => input.fields 来处理这个问题,但我想再次对其进行非规范化,以便非规范化的实体包含此字段结构,因为 API 期望这样。

到目前为止,使用const denormalizedData = denormalize([123], [article], normalizedData.entities) 对我的规范化数据进行非规范化会省略该字段:

[
{
    "author": {
    "id": "1",
    "name": "Paul"
    },
    "title": "My awesome blog post",
    "comments": [
    {
        "id": "324",
        "commenter": {
        "id": "2",
        "name": "Nicole"
        }
    }
    ]
}
]   

我在api docs 中找不到任何关于如何在非规范化上添加额外处理的内容,知道吗?

【问题讨论】:

    标签: normalizr


    【解决方案1】:

    因为processStrategy是用于规范化过程中的数据预处理,所以它不会在非规范化过程中执行。对于您的用例,我不会使用此功能,而只是按如下方式构建您的架构:

    const { schema, denormalize, normalize } = normalizr;
    const user = new schema.Entity("users");
    const comment = new schema.Entity("comments", { commenter: user });
    const commentList = [comment];
    const post = new schema.Entity("posts", {
      fields: { author: user, comments: commentList }
    });
    const postList = [post];
    const mockApiResponse = {
      records: [
        {
          id: "123",
          fields: {
            author: {
              id: "1",
              name: "Paul"
            },
            title: "My awesome blog post",
            comments: [
              {
                id: "324",
                commenter: {
                  id: "2",
                  name: "Nicole"
                }
              }
            ]
          }
        }
      ]
    };
    
    const normalizedResponse = normalize(mockApiResponse.records, postList);
    const denormalizedResponse = denormalize(
      normalizedResponse.result,
      postList,
      normalizedResponse.entities
    );
    
    console.log("normalizedResponse", normalizedResponse);
    console.log("denormalizedResponse", denormalizedResponse);
    

    这将为您提供您正在寻找的结果。如果出于某种原因,您需要坚持当前的实现,我建议您在将请求发送回服务器之前对其进行转换。例如,axios 用他们的transformRequest 功能解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2013-11-04
      • 2010-09-13
      • 1970-01-01
      • 2018-10-22
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多