Search code examples
javascriptjqueryajaxember.jsjquery.fileapi

Using adapter headers outside of ActiveModelAdapter


I've got my authorization system working nicely with Ember Data. All my ember-data calls are signed with the correct tokens by using adapater.ajax() instead of $.ajax. However, I've got a case where I am using a 3rd party upload library which uses its own XHR request (jquery.fileapi). This library exposes a "headers" property for the requests it makes, but I'm not sure what the best way is to get the headers out of my adapter and pass it the file upload component I'm building.

ApplicationAdapter:

export default DS.ActiveModelAdapter.extend({

  namespace: 'api/v1',

  headers: function() {
    var authToken = this.get('session.authToken') || 'None';
    return {
      'Authorization': Ember.String.fmt('Bearer %@', authToken)
    };
  }.property('session.authToken')

});

ImageUploadComponent:

didInsertElement: function() {
  this.$('.js-uploader').fileapi({
    url: '/api/v1/users/avatar',
    accept: 'image/*',
    headers: {'?????????????'}      
  });
}

I'd rather not define a global in "headers" when the 'session.authToken' changes.


Solution

  • Here's what I'm doing for now. Would love other solutions.

    DS.Store.reopen({
    
      apiPathFor: function() {
        var url = arguments.length ? Array.prototype.slice.call(arguments).join('/') : ''
          , adapter = this.adapterFor('application');  
        return [adapter.urlPrefix(), url].join('/');
      }
    
    });
    
    export default Ember.Component.extend({
    
      endpoint: null,
      store: Ember.computed.readOnly('targetObject.store'),
    
      didInsertElement: function() {
    
        var store = this.get('store')
          , adapter = store.adapterFor('application')
          , headers = adapter.get('headers')
          , url = store.apiPathFor(this.get('endpoint'));
    
        var args = {
          url: url,
          headers: headers,
          accept: 'image/*'
        };
    
        this.$('.js-fileapi').fileapi(args);
      },
    
     });