Ember Data Proposal: Fresh / Stale states


#1

Too often I find myself having to create data payloads to ensure that something as simple as retrieving a relationship will have data available. For example

var Speaker = DS.Model.extend({
  presentations: DS.hasMany('presentation')
});

var Presentation = DS.Model.extend({
  speaker: DS.belongsTo('speaker')
});

Assuming the backend has at least one speaker and that speaker has at least one presentation:

speaker.get('presentations') => []

It would be nice if upon first access of a relationship it was assumed the data was not fresh. If it is not fresh ember-data forces a remote request of the data. If it is marked as fresh then ember-data only retrieves locally. I would also expect to easily be able to mark the relationship or the model class itself as stale

speaker.get('presentations') => []
speaker.get('presentations').transtionTo('stale')
speaker.get('presentations') => [Presentation, Presentation]

#2

Couldn’t you just speaker.get('presentations').reload()?


#3

@tomdale what if I have {{#each presentations}} ... {{/each}} in my template? With reload I would have to do something like the following in the route:

model: function(params) {
  var speaker = this.store.find('speaker', params.speaker_id);
  speaker.then(function(model) {
    model.get('presentations').reload();
  });
  return speaker;
}

That seems unnecessarily complex. Not to mention that reload doesn’t seem to exist on the relationship proxy object. Instead something similar to the following is required:

model: function(params) {
  this.store.find('presentation', { speaker_id: prams.speaker_id });
  return this.store.find('speaker', params.speaker_id);
}

Warming the relationship cache like this seems like an extra step that isn’t intuitive. I should be able to get the relationship. If it is my first attempt to access the cold relationship cache ember-data should be smart enough to know that a remote request is required. From there I would have to opt-in to setting the freshness of the relationship.

Considering the current default in ember-data is to always defer to the local cache if this proposal was taken into consideration I would suggest the initial state of the relationship to be stale and then always fresh once warmed unless the developer changes the state. On the first pass I wouldn’t try to get too clever about what actions would transition that state.


#4

@bcardarella regarding stale cache do you have any thoughts on using payloads with partial representations of the resource in response to successful PUT and DELETE requests made from DS.RESTAdapter (or prototypes of it)? One thought I had was using DS.Store#update to apply partial updates (patches) in given a 206 status of the response. See this as well: JSON Patch support for Ember Data