我如何在normalizr.js中表示多对多关系?

时间:2018-07-16 13:10:38

标签: normalizr

我注意到图书馆有了很大的改进,但是我找不到在图书馆中建立多对多关系的方法。

例如,如果我有用户和restos。我的“喜欢”,“访问过”,“ wantToGo”可能有许多不同的关系。我如何在normalizr.js中对其进行规范化?

1 个答案:

答案 0 :(得分:0)

您应该遵循example of this in the normalizr repo。它需要mergeStrategyprocessStrategy的组合:

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];