非规范化逆过程策略

时间:2018-12-10 11:43:34

标签: normalizr

我有一个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中找不到关于如何在非规范化上添加额外处理的任何想法吗?

1 个答案:

答案 0 :(得分:0)

由于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功能解决了这一问题。