denormalise reverse processStrategy
Asked Answered
F

1

6

I have an API that gives out data like this with the attributes in a fields property.

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

When normalizing, I now handle this with a simple processStrategy: (input, parent, key) => input.fields but I would like denormalise this again so that the denormalised entities to contain this fields structure because the API expects it this way.

So far denormalising my normalised data with const denormalizedData = denormalize([123], [article], normalizedData.entities) omits the field:

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

I cannot find anything in the api docs on how to add extra processing on denormalisation, any idea?

Frightened answered 10/12, 2018 at 11:43 Comment(0)
A
0

Because processStrategy is intended for pre-processing of data during the normalization process, it is not going to be executed during the denormalization. For your use case, I would not use this feature and simply structure your schemas as follows:

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);

This will give you the result you are looking for. If for some reason, you need to stick to your current implementation, I would recommend implementing a transform on your request prior to sending it back to the server. As an example, axios solves this with their transformRequest feature.

Aquino answered 5/11, 2019 at 23:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.