Search code examples
normalizr

Normalize linked ids


I have a weird set of data here.

const data = {
    profiles: [
        { name: 'Joe', photos: [1, 2, 3] },
        { name: 'Ryan', photos: [2] },
        { name: 'Bob', photos: null }
    ],
    linked: {
        photos: [
            { id: 1, url: 'http://blah' },
            { id: 2, url: 'blah' },
            { id: 3, url: 'asdf' }
        ]
    }
}

I get all the profiles like this:

const { entities } = normalize(data, {
    profiles: [ Profile ]
});

But I want to replace the photos id array with the entries from linked.photos, is this possible? Or does it require post processing? I am currently doing custom post processing.


Solution

  • I'm not sure that normalizr is the best aproach for your task, but something like this will work

    const photoSchema = new schema.Entity('photos', {});
    const normalized = normalize(data.linked.photos, [photoSchema]);
    const profileRawSchema = new schema.Entity('profiles', {}, {idAttribute: 'name'})
    const profileSchema = new schema.Entity('profiles', {
        photos: [photoSchema]
    }, {idAttribute: 'name'});
    const normalizedProfiles = normalize(
        data.profiles,
        [profileRawSchema]
    );
    
    normalized.entities.profiles = normalizedProfiles.entities.profiles;
    // here is what you want
    const desiredResult = denormalize(normalizedProfiles.result, [profileSchema], normalized.entities);
    

    Docs for denormalize