1
votes

I am working on caching my ember-data store to local storage. On first load I query the server load the data into the store and then load it into local storage. On subsequent page loads I pull the data from localstorage and load it into the store. I am able to do this using the pushMany method.

The store's pushMany method requires normalized data. Payload from the server is normalized by passing it through the models serializer. Once the normalized data is in the store it seems reasonable to believe that it should be possible to pull normalized data out.

So how do you pull normalized data out of the store?

There is a _data property on each model. The '_data' property only works with flat models. More complex models _data property contains instantiated relationships.

I would like to avoid having to serialize/deserialize more than once.

This is my current implementation. The problem with the toJson method is it has to load all the associations including async relations that have not been resolved. I think there is a fundamental issue regarding how ember data resolves relationship primary/foreign keys.

1
I dont know if this is what you mean but you can get records from the store without making a request server by using all - via emberjs.com/guides/models/finding-records/… "To get a list of records already loaded into the store, without making another network request, use all instead." var posts = this.store.all('post'); // => no network requestCraicerjack
this works for models without relationships. IMO there should be a method on the model for extracting the raw normalized data.Aaron Renoir
yeah i was thinking that the solution couldnt be that simple....Craicerjack

1 Answers

2
votes

A good starting point for your problem could be the implementation of toJSON from ember-data.

As you mentioned, the problem with toJSON is that it is resolving all the associations. For belongsTo relationships it's easy to avoid this issue by using _data to get the id of the related object.

customToJSON: function(record) {
  var json = {};
  json.id = record.get('id');

  var serializer = DS.JSONSerializer.create({ container: record.container });

  record.eachAttribute(function(key, attribute) {
    serializer.serializeAttribute(record, json, key, attribute);
  }, this);

  record.eachRelationship(function(key, relationship) {
    if (relationship.kind === 'belongsTo') {
        json[relationship.key] = record._data[relationship.key].id;
    }
  });

  return json;
}