Łukasz Stalmach
Łukasz Stalmach

Reputation: 143

EmberJS and custom endpoints urls

I'm working with EmberJS version 2.14.2 for frontend and I have Rails API backend. I want to get some data from backend but auto-generated url is different from my API endpoint.

the difference is: emberJS generates /admins/api/v1/domains but my endpoint is actually /admins/api/v1/domains.json

how can I achive this in EmberJS? how can i define a totally different endpoint for some models?

my adapter:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  host: 'http://localhost:4000',
  namespace: 'admins/api/v1',
  session: Ember.inject.service('session'),

  headers: Ember.computed('session.access_token', function() {
    return {
      'Authorization': "Bearer " + this.get('session.access_token')
    };
  })
});

my model:

import DS from 'ember-data';

export default DS.Model.extend({
  host: DS.attr(), 
  layout: DS.attr(), 
  token: DS.attr(), 
  created_at: DS.attr(), 
  updated_at: DS.attr()
});

Is it possible to define a custom endpoint in EmberJS? I really checked the documentation and there is nothing there.

Plz halp

Upvotes: 0

Views: 719

Answers (2)

handlebears
handlebears

Reputation: 2276

You can define different adapters for each model in your app. Simply create an adapter that shares the model name using 'ember new adapter modelname'. If a model does not have its own adapter, it will use whatever is in the application adapter.

Take a read through the Customizing Adapters section of the Guides. It describes this feature and more info that you will probably need: https://guides.emberjs.com/v2.14.0/models/customizing-adapters/

Upvotes: 0

Jesper Haug Karsrud
Jesper Haug Karsrud

Reputation: 1193

You have a few different options here. You can override each of the different URL-building methods to always append .json, or you can override the adapter's buildURL method, call this._super(...arguments), and append .json to the resulting URL:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  buildURL: function() {
    const url = this._super(...arguments);
    return `${url}.json`;
  }
});

However, Rails does content negotiation based on the header that is being sent too. This means that you won't have to append .json to your URL's at all.

Ember Data with the JSONAPIAdapter will send the JSON API header application/vnd.api+json, not the regular application/json that Rails expects to do its content negotiation. You can add that header to Rails through an initializer that does Mime::Type.register 'application/vnd.api+json', :json. That tells Rails that when a request comes in with that header, it should interpret it as JSON.

Upvotes: 3

Related Questions