[CORD-873] CRUD for Core and Service model from Chameleon
Change-Id: I45c533feba6720b82de3681d862773047e7fd6f8
diff --git a/src/app/datasources/stores/model.store.ts b/src/app/datasources/stores/model.store.ts
index 291e7c0..4958015 100644
--- a/src/app/datasources/stores/model.store.ts
+++ b/src/app/datasources/stores/model.store.ts
@@ -6,11 +6,11 @@
 import {IStoreHelpersService} from '../helpers/store.helpers';
 
 export interface  IXosModelStoreService {
-  query(model: string): Observable<any>;
+  query(model: string, apiUrl?: string): Observable<any>;
   search(modelName: string): any[];
 }
 
-export class ModelStore implements IXosModelStoreService {
+export class XosModelStore implements IXosModelStoreService {
   static $inject = ['$log', 'WebSocket', 'StoreHelpers', 'ModelRest'];
   private _collections: any; // NOTE contains a map of {model: BehaviourSubject}
   constructor(
@@ -22,59 +22,76 @@
     this._collections = {};
   }
 
-  public query(model: string): Observable<any> {
+  public query(modelName: string, apiUrl: string): Observable<any> {
     // if there isn't already an observable for that item
-    if (!this._collections[model]) {
-      this._collections[model] = new BehaviorSubject([]); // NOTE maybe this can be created when we get response from the resource
-      this.loadInitialData(model);
+    if (!this._collections[modelName]) {
+      this._collections[modelName] = new BehaviorSubject([]); // NOTE maybe this can be created when we get response from the resource
+      this.loadInitialData(modelName, apiUrl);
     }
 
     this.webSocket.list()
-      .filter((e: IWSEvent) => e.model === model)
+      .filter((e: IWSEvent) => e.model === modelName)
       .subscribe(
         (event: IWSEvent) => {
-          this.storeHelpers.updateCollection(event, this._collections[model]);
+          this.storeHelpers.updateCollection(event, this._collections[modelName]);
         },
         err => console.error
       );
 
-    return this._collections[model].asObservable();
+    return this._collections[modelName].asObservable();
   }
 
   public search(modelName: string): any[] {
-    return _.reduce(Object.keys(this._collections), (results, k) => {
-      // console.log(k, this._collections[k].value)
-      const partialRes = _.filter(this._collections[k].value, i => {
-        if (i.humanReadableName) {
-          return i.humanReadableName.toLowerCase().indexOf(modelName) > -1;
+    try {
+      const res =  _.reduce(Object.keys(this._collections), (results, k) => {
+        let partialRes;
+        // NOTE wrapped in a try catch as some subject may be errored, due to not available REST endpoint
+        try {
+          partialRes = _.filter(this._collections[k].value, i => {
+            if (i && i.humanReadableName) {
+              return i.humanReadableName.toLowerCase().indexOf(modelName) > -1;
+            }
+            else if (i && i.name) {
+              return i.name.toLowerCase().indexOf(modelName) > -1;
+            }
+            return false;
+          });
+        } catch (e) {
+          partialRes = [];
         }
-        else if (i.name) {
-          return i.name.toLowerCase().indexOf(modelName) > -1;
-        }
-        return false;
-      })
-        .map(m => {
+        partialRes.map(m => {
           m.modelName = k;
           return m;
         });
-      return results.concat(partialRes);
-    }, []);
+        return results.concat(partialRes);
+      }, []);
+      return res;
+    } catch (e) {
+      return [];
+    }
   }
 
   public get(model: string, id: number) {
     // TODO implement a get method
   }
 
-  private loadInitialData(model: string) {
-    // NOTE check what is the correct pattern to pluralize this
-    const endpoint = this.storeHelpers.urlFromCoreModel(model);
-    this.ModelRest.getResource(endpoint).query().$promise
+  private loadInitialData(model: string, apiUrl?: string) {
+    // TODO provide alway the apiUrl togheter with the query() params
+    if (!angular.isDefined(apiUrl)) {
+      // NOTE check what is the correct pattern to pluralize this
+      apiUrl = this.storeHelpers.urlFromCoreModel(model);
+    }
+    this.ModelRest.getResource(apiUrl).query().$promise
       .then(
         res => {
           this._collections[model].next(res);
         })
       .catch(
-        err => this.$log.log(`Error retrieving ${model}`, err)
+        // TODO understand how to send an error to an observable
+        err => {
+          this._collections[model].error(err);
+          // this.$log.log(`Error retrieving ${model}`, err);
+        }
       );
   }
 }