samedi 2 janvier 2016

Serialize a DS.RecordArray to the jsonapi.org format?

Assume you have an ember-data model like this:

// foo.js
export default DS.Model.extend({
    name: DS.attr('string'),
    alpha: DS.belongsTo('alpha'),
    betas: DS.hasMany('beta'),
    gammas: DS.hasMany('gamma')
}

And at some point, you have obtained a model via:

//...
model = this.store.peekAll('foo');
//...

Question: How do you serialize this DS.RecordArray into the jsonapi.org format?

Constraints:

  1. The server is 'read-only'. Not my hardware or server, so I can't change that, nor can I afford to stand up a public server for general use.
  2. The original data did not come in JSON format, it had to be transformed by a custom serializer.
  3. The user will customize the original data to their needs, so reloading the original data isn't viable.
  4. The 'alpha' and 'betas' must be included in the "include" section of the JSON as specified by jsonapi.org. While they are separate records, they are part of the 'foo' data feed and need to be incorporated in the JSON.
  5. The 'gammas' come from a separate feed, so you only need to record the fact of the relationship, not the actual data in the 'gamma' record. The 'gamma' records are loaded prior to loading the 'foo' records, so 'async' is not an issue.
  6. You are permitted to add necessary options to the model elements, but the basic structure must remain.
  7. Custom code to manually perform the entire serialization is not desired. I already know how to do that, it just seems absurd since DS.JSONAPISerializer already understands the desired format.

Intent:

Provide the JSON to the user such that they can save it for future use.

Discussion:

Theoretically, the DS.JSONAPISerializer's 'serialize' method should be able to do this. After all, that's the class that would end up loading this data back into the application. Unfortunately, there doesn't seem to be a method to get a DS.Snapshot of a DS.RecordArray to feed to the serializer. The best I've found is to use a SINGLE RECORD model's 'serialize' method to get the corresponding JSON. That's not suitable for what I want to do.

this.store.find('foo','32').then(function(x) {
    console.log(JSON.stringify(x.serialize()));
});

The discussion I've seen regarding 'snapshot' on one ember-data issue indicates that they didn't want to make the function for creating a snapshot public, but that discussion was only about single records, not record arrays.




Aucun commentaire:

Enregistrer un commentaire