Sophie McCarrell
Sophie McCarrell

Reputation: 2871

How do i represent a many to many relationship in normalizr.js?

I noticed the library was greatly improved, but I couldn't find how to do a many to many relationship in the library.

For example, if I have users, and restos. I may have "likes", "visited", "wantToGo" all as different many to many relationships. How would I normalize that in normalizr.js?

Upvotes: 0

Views: 642

Answers (1)

Paul Armstrong
Paul Armstrong

Reputation: 7156

There's an example of this in the normalizr repo that you should follow. It requires a combination of a mergeStrategy and processStrategy:

import { schema } from '../../src';

const userProcessStrategy = (value, parent, key) => {
  switch (key) {
    case 'author':
      return { ...value, posts: [parent.id] };
    case 'commenter':
      return { ...value, comments: [parent.id] };
    default:
      return { ...value };
  }
};

const userMergeStrategy = (entityA, entityB) => {
  return {
    ...entityA,
    ...entityB,
    posts: [...(entityA.posts || []), ...(entityB.posts || [])],
    comments: [...(entityA.comments || []), ...(entityB.comments || [])]
  };
};

const user = new schema.Entity(
  'users',
  {},
  {
    mergeStrategy: userMergeStrategy,
    processStrategy: userProcessStrategy
  }
);

const comment = new schema.Entity(
  'comments',
  {
    commenter: user
  },
  {
    processStrategy: (value, parent, key) => {
      return { ...value, post: parent.id };
    }
  }
);

const post = new schema.Entity('posts', {
  author: user,
  comments: [comment]
});

export default [post];

Upvotes: 1

Related Questions