ngrx / data-如何编写自定义的reducer来处理返回多个实体的端点?

时间:2019-08-16 20:20:06

标签: ngrx angular-ngrx-data

我当前正在尝试将我的ngrx存储转换为使用ngrx / data处理我的实体。我遇到的棘手的障碍之一是处理API端点,这些端点返回多个实体的数据。一个简单的例子-可以说我有以下模型可以从我的API中检索:

export interface Parent {
  id: string;
  name: string;
}

export interface Child {
  id: string;
  name: string;
  parent: string
}

我有以下端点:

/api/parents              #GET (list of parents), POST (create new parent)
/api/parents/<PARENT_ID>  #GET, PATCH, PUSH, DELETE (a single parent)
/api/children             #GET (list of children), POST (create new child)
/api/children/<CHILD_ID>  #GET, PATCH, PUSH, DELETE (a single child)
/api/families             #GET (all parents and children)

/api/families是一种便捷功能,它以以下格式返回所有父母和子女:

{
  parents: Parent[];
  children: Child[];
}

过去,我为ngrx存储创建了一个单独的families条目,仅包含加载/加载的参数,然后执行了一组LoadFamilies操作以从服务器获取数据。然后,我将这些动作包含在“父母和子女的商店减少者”中,并对其采取适当的措施。我现在想做的就是将此额外的reducer添加到我现有的ngrx /数据控制的实体中。有关如何解决此问题的任何想法/示例代码?

1 个答案:

答案 0 :(得分:2)

扩展DefaultDataService参见https://ngrx.io/guide/data/entity-dataservice#custom-entitydataservice

在管道图中将数据嵌套到实体(我使用normalizr)

然后使用EntityActionFactory as eaFactory使用您认为合适的方式来更新实体商店的调度实体缓存操作

带有Parent <-> ConcreteRecordHeader的子元素<-> ConcreteRecordLoad

的示例
  getById(key: string | number): Observable<ConcreteRecordHeader> {
    return super.getById(key).pipe(
      map((denorm: any) =>
        this.categoryCacheService.normalizeCategory([denorm])
      ),
      tap((norm: NormalizedCategories) => this.mergeQuerySet(norm)),
      map((norm: NormalizedCategories) => this.pickEntities(norm)[0])
    ) as Observable<ConcreteRecordHeader>;
  }

  protected mergeQuerySet(norm: NormalizedCategories) {
    console.log("⚠️ Merging server data ⚠️");
    const options: EntityActionOptions = {
      mergeStrategy: MergeStrategy.PreserveChanges
    };
    const data = norm.entities.concreteRecordLoads
      ? Object.values(norm.entities.concreteRecordLoads)
      : [];
    const action = this.eaFactory.create(
      "ConcreteRecordLoad",
      EntityOp.SAVE_UPSERT_MANY_SUCCESS,
      data,
      options
    );
    this.entityCacheDispatcher.dispatch(action);
  }

  protected pickEntities(norm: NormalizedCategories) {
    return (norm.entities.concreteRecordHeaders
      ? Object.values(norm.entities.concreteRecordHeaders)
      : []) as ConcreteRecordHeader[];
  }

不幸的是,this.entityCacheDispatcher.mergeQuerySet()无法使用mergeStrategy(这是要使用的自然API)。我打算为此提交PR。