@NgRx how to Many to Many relationship between entities?

Viewed 613

Let say i have this state:

{
  "appointments": {
    "ids": [...],
    "entities": [
        "0": {
            ...
            mandatoryRecipients: ['0','3']
        },
        "1": {
            ...
            mandatoryRecipients: ['1','2','0']
        }
    ]
  },
  "recipients": {
    "ids": [...],
    "entities": [
        "0": {
            ...
            id: '0',
            name: 'foo'
        },
        "1": {
            ...
            id: '1',
            name: 'foobar'
        },
        "2": {
            ...
            id: '2',
            name: 'bar'
        }
    ]
  }
}

At a certain point, I need to add a value into the 'mandatoryRecipients' array of the appointment entity. I know that this state is not normalized but how can I normalize it in order to accomplish a many to many relationship?

2 Answers

You need to use a lib for that. Manually it will take too much effort to cover everything.

You can use ngrx-entity-relationship.

Like that for example.

const fullAppointment = rootEntity(
  selectAppointments, // feature selector, EntityState<Appointment>
  relatedEntity(
    selectRecipients, // related feature selector, EntityState<Recipient>
    'mandatoryRecipients', // key with ids
    'mandatoryRecipientsEntities', // key to assign related entities
  ),
);

const fullAppointments = rootEntities(fullAppointment);

store.select(fullAppointments, ['0', '1']).subscribe(value => {
  // value[0].mandatoryRecipientsEntities[0].name works!
});

or if you use createSelector then

const selectFullAppointments = createSelector(
  selectIds,
  v => v,
  (ids, store) => fullAppointments(store, ids);
);
 interface Appointment {
  id: string;
}

 interface MandatoryRecepient {
   id: string;
   recepientId: string;
   appointmentId: string;
 }

 interface Recepient {
  id: string;
  name: string;
}
Related