Skip to content

Instantly share code, notes, and snippets.

@chadhietala
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save chadhietala/692b4829c014487f5ec9 to your computer and use it in GitHub Desktop.

Select an option

Save chadhietala/692b4829c014487f5ec9 to your computer and use it in GitHub Desktop.
Models in Ember

URLS And APIs

In Ember everything developed around the URL. In an Ember application you define your routes in a DSL that looks like the following.

Ember.Router.map(function () {
   this.resource('profile', { path: '/:profile_id' });
});

So when a user goes to profile/123 what happens that URL maps to ProfileRoute where the url is serialized and passed to the model hook so you can ask the data store to preform a GET on /api/profile/123.

var ProfileRoute = Ember.Route.extend({
  model: function ( params ) {
    console.log( params ) // { profile_id: 123 }
    return this.store.find('profile', params.profile_id ); // Make API request to /api/profile/123
  }
});

Given the following model definitions:

var Profile = DS.Model.extend({
  firstName: DS.attr('string')
  connections: DS.hasMany('connection')
  ...
});

var Connection = DS.Model.extend({
  name: DS.attr('string')
  ...
});

I should receive JSON that looks like the following.

{
  profile: {
    id: 123,
    firstName: 'Chad'
    connections: [1,23]
    ...
  },
  connections: [
    {
      id: 1,
      name: 'Foo'
    },
    {
      id: 23,
      name: 'Bar'
    }
  ]
}

If the data does not look like this I have to implement a serializer to turn the passed back format into the flattened structure. This is because the models in Ember Data are defined as flat structures where the relations are keyed off of ID. In the model definition, it is implied that the data will have an id.

If the id field does not exist I have to tell the serializer what the primary key is. This complicates things further because the URN is currently being used but the URN is not what comes in the URL.

Caching

I also don't have to worry about caching, as that is taken care of as well. We could cache to disk for offline functionality pretty easily using something like Ember Sync.

Immutable Models

By design records created from a Model use the immutable model instance. I believe this is in line for what the iOS client wants.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment