反正义逆向过程策略

jor*_*sjh 6 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"
            }
        }
        ]
    }
    }
]
};
Run Code Online (Sandbox Code Playgroud)

在规范化时,我现在用一个简单的方法处理它,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"
        }
    }
    ]
}
]   
Run Code Online (Sandbox Code Playgroud)

我在api文档中找不到关于如何在非规范化上添加额外处理的任何内容,任何想法?

Bri*_*wis 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);
Run Code Online (Sandbox Code Playgroud)

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