import Ember from 'ember';
import _ from 'lodash';
import store from 'corpus-common-addon/utils/store';
const DEFAULT_DEBOUNCE = 10;
export default Ember.Service.extend({
promises: null,
queryRegister: null,
storeKeyBase: null,
apiPath: null,
resDocRoot: null,
processId: function (id) {
return id;
},
getReturnDictKey: function (id) {
return id;
},
init(...args) {
this._super(...args);
this.set('promises', []);
this.set('queryRegister', {});
this.doQuery = _.debounce(this._doQuery, DEFAULT_DEBOUNCE);
},
env: function () {
return Ember.getOwner(this).resolveRegistration('config:environment');
},
_getStoreKey: function (id) {
return this.storeKeyBase + ':' + id;
},
_doQuery: function () {
const queryRegister = this.get('queryRegister');
this.set('queryRegister', {});
const ids = Object.keys(queryRegister).join(',');
if (!ids) {
_.each(queryRegister, resolveReject=> {
resolveReject[0]({});
});
}
Ember.$.ajax({
// TODO Configuration ?
url: this.env().APP.backRootURL.replace(/\/$/, '') + this.apiPath + ids,
success: itemDoc=> {
_.each(queryRegister, resolveReject=> {
resolveReject[0](itemDoc[this.resDocRoot]);
});
},
error: (req, status, error)=> {
_.each(queryRegister, resolveReject=> {
resolveReject[1](status + ':' + error);
});
}
});
},
// make the query for the name.
// return a Promise
queryName: function (id) {
const queryRegister = this.get('queryRegister');
return new Ember.RSVP.Promise(function (resolve, reject) {
queryRegister[id] = [resolve, reject];
this.doQuery(this);
}.bind(this));
},
getName: function (id) {
if (!id) {
return new Ember.RSVP.Promise(function (resolve/* , reject*/) {
resolve('');
});
}
const objectId = this.processId(id);
let namePromise = null;
const storeKey = this._getStoreKey(id);
const name = store.get(storeKey);
if (name !== null) {
namePromise = new Ember.RSVP.Promise(function (resolve/* , reject*/) {
resolve(name);
});
} else if (storeKey in this.get('promises')) {
namePromise = this.get('promises')[storeKey];
} else {
// handle error !!!
namePromise = this.queryName(objectId)
.then(function (names) {
delete this.get('promises').storeKey; /* eslint prefer-reflect: "off" */
return store.set(storeKey, names[this.getReturnDictKey(objectId)]);
}.bind(this));
this.get('promises')[storeKey] = namePromise;
}
return namePromise;
}
});