common/corpus-common-addon/app/services/lexvo-resolver.js
author ymh <ymh.work@gmail.com>
Sun, 28 Feb 2016 09:30:23 +0100
changeset 134 c06d08c8a1b8
parent 127 5cd8c3065c38
child 182 1bcc373adabb
permissions -rw-r--r--
add bnf resolver in common addon + applications

import Ember from 'ember';
import store from 'corpus-common-addon/utils/store';
import * as constants from 'corpus-common-addon/utils/constants'

export default Ember.Service.extend({
  env: function() {
    return Ember.getOwner(this).resolveRegistration('config:environment')
  },
  _getStoreKey: function(id) {
    return 'lexvo:'+id;
  },
  getName: function(id) {

    if(!id) {
      return new Ember.RSVP.Promise(function(resolve/*, reject*/) {
        resolve("");
      });
    }

    var lexvoId = id;
    if(id.startsWith(constants.LEXVO_BASE_URL)) {
      lexvoId = id.slice(constants.LEXVO_BASE_URL.length);
    }
    var namePromise = null;

    var storeKey = this._getStoreKey(id);
    var name = store.get(storeKey);

    if(!name) {
      //TODO: handle error !!!
      namePromise = this.queryName(lexvoId)
        .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: this.env().baseURL.replace(/\/$/,"") + "/api/v1/lexvo/"+id,
        success: function(lexvoDoc) {
          var names = lexvoDoc.lexvoids;
          resolve((id in names)?names[id]:null);
        },
        error: function(req, status, error) {
          reject(status + ":" + error);
        }
      });
    }.bind(this));
  }
});