28
|
1 |
import Ember from 'ember'; |
|
2 |
import store from 'store'; |
|
3 |
import ENV from 'bo-client/config/environment'; |
|
4 |
|
|
5 |
// TODO: implement store layer with auto-expiration : c.f. https://github.com/marcuswestin/store.js/#no-sessionstorageauto-expiration |
|
6 |
export default Ember.Service.extend({ |
|
7 |
constants: Ember.inject.service(), |
|
8 |
_getStoreKey: function(id) { |
|
9 |
return 'viaf:'+id; |
|
10 |
}, |
|
11 |
getName: function(id) { |
|
12 |
var viafId = id; |
|
13 |
if(id.startsWith(this.get('constants').VIAF_BASE_URL)) { |
|
14 |
viafId = id.slice(this.get('constants').VIAF_BASE_URL.length); |
|
15 |
} |
|
16 |
var storeKey = this._getStoreKey(id); |
|
17 |
var namePromise = null; |
|
18 |
|
|
19 |
var name = store.get(storeKey); |
|
20 |
if(!name) { |
|
21 |
//TODO: handle error !!! |
|
22 |
namePromise = this.queryName(viafId) |
|
23 |
.then( function(response) { |
|
24 |
return store.set(storeKey, response); |
|
25 |
}); |
|
26 |
} |
|
27 |
else { |
|
28 |
namePromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) { |
|
29 |
resolve(name); |
|
30 |
}); |
|
31 |
} |
|
32 |
return namePromise; |
|
33 |
}, |
|
34 |
// make the query for the name. |
|
35 |
// return a Promise |
|
36 |
queryName: function(id) { |
|
37 |
return new Ember.RSVP.Promise(function(resolve, reject) { |
|
38 |
Ember.$.ajax({ |
|
39 |
//TODO Configuration ? |
|
40 |
url: 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 |
}); |