hino / app / adapters / application.js
application.js
Raw
//export { default } from 'ember-local-storage/adapters/local';

import DS from 'ember-data';
import config from '../config/environment';
// import { classify } from '@ember/string';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import { inject as service } from '@ember/service';
import { computed, get } from '@ember/object';
import $ from 'jquery';

import MethodNotAllowedError from './method-not-allowed-error';
import InternalServerError from './internal-server-error';
import NotFoundError from './not-found-error';

const { JSONAPIAdapter } = DS;

export default JSONAPIAdapter.extend(DataAdapterMixin, {
  host: config.APP.api.host,
  session: service(),
  headers: computed('session.data.authenticated.access_token', {
    get() {
      const headers = {};
      if(this.session.isAuthenticated) {
        headers['Authorization'] = `Bearer ${this.session.data.authenticated.access_token}`;
      }

      return headers;
    }
  }),
  urlForFindRecord(id, modelName, snapshot) {
    let url = this._super(...arguments);
    let query = get(snapshot, 'adapterOptions.query');
    if (query) {
      url += '?' + $.param(query);
    }
    return url;
  },
  handleResponse(status) {
    if (405 === status) {
      return new MethodNotAllowedError();
    }
    // if (500 === status) {
    //   return new InternalServerError();
    // }
    if (404 === status) {
      return new NotFoundError();
    }

    return this._super(...arguments);
  }
});

// authorize(xhr) {
  //   let { access_token } = this.get('session.data.authenticated');
  //   xhr.setRequestHeader('Authorization', `Bearer ${access_token}`);
  // }

  /*
export default class ApplicationAdapter extends DS.JSONAPIAdapter {
  namespace = config.APP.api.namespace;
  host = config.APP.api.host;
}*/