Precise host in ember-data-url-templates


#1

I’m using ember-data-url-templates add-on in Ember 3.1 app. This add-on has an option hostto pass in as follows:

// adapters/comment

import Ember from "ember";
import DS from "ember-data";
import UrlTemplates from "ember-data-url-templates";

export default DS.RESTAdapter.extend(UrlTemplates, {
  urlTemplate: '{+host}/comments{/id}',
  queryUrlTemplate: '{+host}/comments{?query*}',
  createRecordUrlTemplate: '{+host}/users/{userId}/comments',

  session: Ember.inject.service(),

  urlSegments: {
    userId() {
      return this.get('session.userId');
    }
  }
});

How to make use of ENV.apiHost = 'http://localhost:3000';defined in environment.js file ?

I tried to define localhost:3000 for development:

if (environment === 'development') {
    ENV.apiHost = 'http://localhost:3000';
...

I defined it to use in application.js adapter:

#adapters/application.js

export default JSONAPIAdapter.extend(DataAdapterMixin, {
  authorizer: 'authorizer:application',
  host: config.apiHost,
...

If I start the Ember app pass in --proxy='http://localhost:3000 option , everything works. However, I believed that I could omit this option as it is already defined.

So if start the app without proxy option, it fails because it tries to request localhost:4200...:

GET http://localhost:4200/shops/613/address 404 (Not Found)

Any idea ? Thank you.


#2

I figured out myself. I had to prefix the value urlTemplate with {+host} as follows in all the adapters using this add-on:

import ApplicationAdapter from './application';
import UrlTemplates from "ember-data-url-templates";

export default ApplicationAdapter.extend(UrlTemplates, {
  urlTemplate: '{+host}/shops/{shopId}/address',

 urlSegments: {
    shopId: function(type, id, snapshot, query) {
      if (query && query.shop_id) {
        return query.shop_id;
      }
      return snapshot.belongsTo('shop', { id: true });
    },

    id: function(type, id, snapshot/*, query*/) {
      return snapshot.id;
    }
  }

Hope this helps.