common/corpus-common-addon/app/services/viaf-resolver.js
changeset 132 d97eda8bc8ec
child 182 1bcc373adabb
equal deleted inserted replaced
131:31a5c314d575 132:d97eda8bc8ec
       
     1 import Ember from 'ember';
       
     2 import store from 'corpus-common-addon/utils/store';
       
     3 import * as constants from 'corpus-common-addon/utils/constants'
       
     4 
       
     5 export default Ember.Service.extend({
       
     6   env: function() {
       
     7     return Ember.getOwner(this).resolveRegistration('config:environment')
       
     8   },
       
     9   _getStoreKey: function(id) {
       
    10     return 'viaf:'+id;
       
    11   },
       
    12   getName: function(id) {
       
    13     var viafId = id;
       
    14     if(id.startsWith(constants.VIAF_BASE_URL)) {
       
    15       viafId = id.slice(constants.VIAF_BASE_URL.length);
       
    16     }
       
    17     var storeKey = this._getStoreKey(id);
       
    18     var namePromise = null;
       
    19 
       
    20     var name = store.get(storeKey);
       
    21     if(!name) {
       
    22       //TODO: handle error !!!
       
    23       namePromise = this.queryName(viafId)
       
    24         .then( function(response) {
       
    25             return store.set(storeKey, response);
       
    26         });
       
    27     }
       
    28     else {
       
    29       namePromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) {
       
    30         resolve(name);
       
    31       });
       
    32     }
       
    33     return namePromise;
       
    34   },
       
    35   // make the query for the name.
       
    36   // return a Promise
       
    37   queryName: function(id) {
       
    38     return new Ember.RSVP.Promise(function(resolve, reject) {
       
    39       Ember.$.ajax({
       
    40         url: this.env().baseURL.replace(/\/$/,"") + "/api/v1/viaf/"+id,
       
    41         success: function(viafDoc) {
       
    42           var names = viafDoc.viafids;
       
    43           resolve((id in names)?names[id]:null);
       
    44         },
       
    45         error: function(req, status, error) {
       
    46           reject(status + ":" + error);
       
    47         }
       
    48       });
       
    49     }.bind(this));
       
    50   }
       
    51 });