Skip to content
Snippets Groups Projects
data.service.ts 1.76 KiB
Newer Older
Art Lowel's avatar
Art Lowel committed
import { OpaqueToken } from "@angular/core";
import { Observable } from "rxjs";
import { Store } from "@ngrx/store";
Art Lowel's avatar
Art Lowel committed
import { ObjectCacheService } from "../cache/object-cache.service";
import { CacheableObject } from "../cache/object-cache.reducer";
import { RequestCacheState } from "../cache/request-cache.reducer";
import { FindAllRequestCacheAction, FindByIDRequestCacheAction } from "../cache/request-cache.actions";
Art Lowel's avatar
Art Lowel committed
import { ParamHash } from "../shared/param-hash";
import { isNotEmpty } from "../../shared/empty.util";

export abstract class DataService<T extends CacheableObject> {
  abstract name: OpaqueToken;

  constructor(
Art Lowel's avatar
Art Lowel committed
    private store: Store<RequestCacheState>,
    private objectCache: ObjectCacheService
Art Lowel's avatar
Art Lowel committed
  ) { }

  findAll(scopeID?: string): Observable<Array<T>> {
    const key = new ParamHash(this.name, 'findAll', scopeID).toString();
Art Lowel's avatar
Art Lowel committed
    this.store.dispatch(new FindAllRequestCacheAction(key, this.name, scopeID));
Art Lowel's avatar
Art Lowel committed
    //get an observable of the IDs from the store
Art Lowel's avatar
Art Lowel committed
    return this.store.select<Array<string>>('core', 'cache', 'request', key, 'resourceUUIDs')
Art Lowel's avatar
Art Lowel committed
      .flatMap((resourceUUIDs: Array<string>) => {
        // use those IDs to fetch the actual objects from the cache
Art Lowel's avatar
Art Lowel committed
        return this.objectCache.getList<T>(resourceUUIDs);
Art Lowel's avatar
Art Lowel committed
      });
  }

  findById(id: string): Observable<T> {
    const key = new ParamHash(this.name, 'findById', id).toString();
Art Lowel's avatar
Art Lowel committed
    this.store.dispatch(new FindByIDRequestCacheAction(key, this.name, id));
    return this.store.select<Array<string>>('core', 'cache', 'request', key, 'resourceUUIDs')
Art Lowel's avatar
Art Lowel committed
      .flatMap((resourceUUIDs: Array<string>) => {
        if(isNotEmpty(resourceUUIDs)) {
Art Lowel's avatar
Art Lowel committed
          return this.objectCache.get<T>(resourceUUIDs[0]);
Art Lowel's avatar
Art Lowel committed
        }
        else {
          return Observable.of(undefined);
        }
      });
  }

}