How to add multiple entities to store using ngrx/data saveEntities?

821 Views Asked by At

I am trying to add multiple entities to the store using ngrx/data -> saveEntities. So far I got this:

@Injectable()
export class MaintenanceEntityService extends EntityCollectionServiceBase<Maintenance> {

  constructor(
    private serviceElementsFactory: EntityCollectionServiceElementsFactory,
    private entityCacheDispatcher: EntityCacheDispatcher) {
    super('Maintenance', serviceElementsFactory);
  }

  addBatch(maintenances: Maintenance[]) {
    const changes: ChangeSetItem[] = [
      cif.add('Maintenance', maintenances)
    ];
    const changeSet: ChangeSet = { changes, tag: 'Creating alert batch'};

    return this.entityCacheDispatcher.saveEntities(changeSet, `${environment.API}maintenances`).pipe(
      map(response => response)
    );
  }
}

My endpoint receives and return an object like this:

interface ChangeSet<T = any> {
  changes: ChangeSetItem[]
  extras?: T
  tag?: string
}

In the backend I insert all entities into the database and then before returning the same object I update ids, but once again in the Angular app, the store is not getting updated. Am I missing something?

https://ngrx.io/api/data/EntityCacheDispatcher#saveentities

2

There are 2 best solutions below

0
Steven Rojas On

Ok, the ChangeSet object has a property called ChangeSetItem with the next structure:

type ChangeSetItem = ChangeSetAdd | ChangeSetDelete | ChangeSetUpdate | ChangeSetUpsert;

interface ChangeSetAdd<T = any> {
  op: ChangeSetOperation.Add
  entityName: string
  entities: T[]
}

So I need to return the corresponding entityName from the backend so it can be added to the store: In my case: Maintenance

Not sure why the property is not being set in this line:

const changes: ChangeSetItem[] = [
      cif.add('Maintenance', maintenances)
    ];
0
mounds On

Set entityName on the ChangeSet when you create it.

const changeSet: ChangeSet = { 
    entityName: 'Maintenance',
    changes, 
    tag: 'Creating alert batch'
};

This should ensure it's there for the full round trip. Its not clear from your example what cif is but it seems it will only apply to the ChangeSetItem, not the ChangeSet.

Secondly, though this may not concern you, if your server is assigning id's to your saved entities, you need Pessimistic saves enabled - this can be done at various extension points. If Optimistic save is enabled, I don't think ngrx does anything with your ChangeSet on success - eg. New ids would not be assigned to new entities.