normalizr v3 and JSON api

501 views Asked by At

I want to normalise the responses I receive from an API. A typical response could look something like this:

// Get all projects
{data:[
    {
        id: 1
        ...
        team:{
            data: {
                id:15
                ...
            }

        }
    },
    {
        id:2,
        ....
    },
    {
        id:3,
        ...
    }
]}

How do I write my schemas so that it removes the 'data' container? Currently, my schema looks like:

export const project = new schema.Entity('projects', {
    team: team, // team omitted
},
{
    processStrategy: (value, parent, key) => parent.data
}
)

export const arrayOfProjects = new schema.Array(project)

And I am using it like:

const normalizedProjects = normalize(jsonResponse, arrayOfProjects)

normalizedProjects then looks like this:

{
    entities:{
        projects:{
            undefined:{
                0:{
                    team:{
                        data:{
                            id:15,
                            ...
                        }
                    }
                },
                1:{...},
                2:{...}.
                ...
                50:{...},
            }
        }
    },
    result:[] // length is 0
}

I'm not sure why the list of projects is contained in 'undefined', either?

2

There are 2 answers

4
Paul Armstrong On

Each of your entity schema that you want to have the data omitted (or anything else fundamentalyl changed) needs to include a processStrategy that you write to remove or change any data. (see more examples in the tests)

0
Daisuke Kohgami On

I also use json_api schema. How about like this?

const projectsSchema = new schema.Entity('projects', {}, {
  processStrategy: processStrategy
});

export const processStrategy = (value, parent, key) => {
  const attr = value.attributes;
  delete value.attributes;
  return { ...value, ...attr };
};

export const fetchProjectsSchema = {
  data: [projectsSchema]
}