Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flatten many-to-many relationships within a Redux state using Normalizr?

Scenario

We have a database that maps the following relationship:

  • A tag has many campaigns
  • A campaign has many tags
  • The relationship between campaigns and tags is represented by an associative entity called a campaign_tag
  • The campaign_tag entity has a priority attribute

Question

How can we implement normalizr (or any similar library) to generate a flattened app state that accounts for our associative entities, when our associative entities do not have unique IDs / values?

Notes / Misc Thoughts

Other examples I've seen only had the original entities mapped out and seem better suited for one-to-many or one-to-one relationships. They usually produced state tree such as this:

{
  entities: {
    campaigns: {
      '1': { id: 1, name: 'Ace', tags: [1, 2, 3] },
      ...
    },
    tags: {
      '1': { id: 1, name: 'Example Tag', campaigns: [1, 2, 3] },
      ...
    }
  },
  ...
}

Would our associative entities go in that entities group? Should we just add unique IDs? That seems counter-productive. Is it even appropriate to flatten such relationships?

Any help is appreciated, thanks.

like image 650
MSD Avatar asked Oct 30 '22 23:10

MSD


1 Answers

Scenarios:

  1. You control the API: I'll send objects like this:

    campaigns: [{
      id: <id>,
      name: <name>,
    }],
    tags: [{ id: <id>, name: <name> }],
    campaign_tags: [{campaign_id, tag_id, priority}]
    

    So this will be easy to manage and avoid duplication of information. When you mount your component using redux connect, you can create a selector to fill your campaign tags to add to your component's properties.

  2. You don't control the API. In this case I'll need to know what type of response are you getting from the server in order to recommend something.

like image 177
Franco Risso Avatar answered Nov 09 '22 09:11

Franco Risso