server/bo_client/app/services/viaf-resolver.js
changeset 28 b0b56e0f8c7f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/server/bo_client/app/services/viaf-resolver.js	Fri Jan 15 15:35:00 2016 +0100
@@ -0,0 +1,51 @@
+import Ember from 'ember';
+import store from 'store';
+import ENV from 'bo-client/config/environment';
+
+// TODO: implement store layer with auto-expiration : c.f. https://github.com/marcuswestin/store.js/#no-sessionstorageauto-expiration
+export default Ember.Service.extend({
+  constants: Ember.inject.service(),
+  _getStoreKey: function(id) {
+    return 'viaf:'+id;
+  },
+  getName: function(id) {
+    var viafId = id;
+    if(id.startsWith(this.get('constants').VIAF_BASE_URL)) {
+      viafId = id.slice(this.get('constants').VIAF_BASE_URL.length);
+    }
+    var storeKey = this._getStoreKey(id);
+    var namePromise = null;
+
+    var name = store.get(storeKey);
+    if(!name) {
+      //TODO: handle error !!!
+      namePromise = this.queryName(viafId)
+        .then( function(response) {
+            return store.set(storeKey, response);
+        });
+    }
+    else {
+      namePromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) {
+        resolve(name);
+      });
+    }
+    return namePromise;
+  },
+  // make the query for the name.
+  // return a Promise
+  queryName: function(id) {
+    return new Ember.RSVP.Promise(function(resolve, reject) {
+      Ember.$.ajax({
+        //TODO Configuration ?
+        url:  ENV.baseURL.replace(/\/$/,"") + "/api/v1/viaf/"+id,
+        success: function(viafDoc) {
+          var names = viafDoc.viafids;
+          resolve((id in names)?names[id]:null);
+        },
+        error: function(req, status, error) {
+          reject(status + ":" + error);
+        }
+      });
+    }.bind(this));
+  }
+});