13

I would like to set my RESTAdapter host based on the build environment.

I assume the value can be stored in config/environment.js like this:

if (environment === 'development') {
  ENV.API_ENDPOINT = 'http://localhost:8080';
}

if (environment === 'production') {
  ENV.API_ENDPOINT = 'http://api.myserver.com';
}

But I am unsure how to insert the information into adapter/application.js during the build process.

Weston
  • 2,732
  • 1
  • 28
  • 34

1 Answers1

24

You define the setting like this in your config/environment.js:

  // snip
  APP: {
    // Here you can pass flags/options to your application instance
    // when it is created
    API_HOST: 'http://192.168.1.37:3000' // default setting
  }
};

if (environment === 'development') {
  ENV.APP.LOG_TRANSITIONS = true;
  ENV.APP.API_HOST = 'http://192.168.1.37:3000'; // override
}

You can then use the setting in other files like this:

// app/adapters/application.js:
import DS from "ember-data";

export default DS.RESTAdapter.extend({
   host: window.MyAppENV.APP.API_HOST
});

Replace MyApp with your application.

You switch to a build environment with the ember --environment option:

ember serve --environment production

or

ember build --environment development

I've not seen yet whether there is a way to provide the value dynamically, but you can provide as many environments as you want of course.

Update: Adding for completeness, and as per Weston's comment, Environments documents this functionality.

Leeft
  • 3,827
  • 1
  • 17
  • 25
  • What you have is exactly what I needed. Dynamically may have been misleading, I meant picking the environment during build. – Weston Aug 07 '14 at 18:21
  • 1
    Now that I know what to ask I found the documentation on [Environments](http://www.ember-cli.com/#Environments) – Weston Aug 07 '14 at 18:39
  • Does this solution still work for ember version: 0.1.0 node: 0.10.28 npm: 1.5.0-alpha-4 – millisami Oct 13 '14 at 15:20
  • 1
    @Millisami I've updated the answer above for the current mechanism. It changed with 0.0.47 – Weston Nov 04 '14 at 20:47
  • 1
    also see: http://stackoverflow.com/questions/24902918/retain-fixtures-with-multiple-adapters-per-ember-environment?answertab=active#tab-top – house9 Nov 11 '14 at 17:27
  • 6
    I must be doing something wrong, but when I reference window.EmberENV.APP.API_HOST, I get the error 'Cannot read property 'API_HOST' of undefined'. window.EmberENV is defined, but window.EmberENV.APP is undefined. What am I missing here? – jwoww Apr 28 '15 at 06:51