Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember data 1.0.0: confused with per-type adapters and serializers

I am migrating from Ember data 0.13 to 1.0.0 beta. According to the doc https://github.com/emberjs/data/blob/master/TRANSITION.md, there are now per type adapters and per type serializers.

This means that I can no longer define a "myRestAdapter" with some specific overrides for the primary key and the authentication. I need to implement this code now for each model type resulting in duplicating xx times the same code.

Code in Ember data 0.13:

App.AuthenticatedRestAdapter = DS.RESTAdapter.extend({  

  serializer: DS.RESTSerializer.extend({
    primaryKey: function() {
      return '_id';
    }
  }),

  ajax: function (url, type, hash) {
    hash = hash || {};
    hash.headers = hash.headers || {};
    hash.headers['Authorization'] = App.Store.authToken;
    return this._super(url, type, hash);
  }
});

Code in Ember data 1.0.0 (only for setting the primary key to _id instead of _id:

App.AuthorSerializer = DS.RESTSerializer.extend({

  normalize: function (type, property, hash) {
    // property will be "post" for the post and "comments" for the
    // comments (the name in the payload)

    // normalize the `_id`
    var json = { id: hash._id };
    delete hash._id;

    // normalize the underscored properties
    for (var prop in hash) {
      json[prop.camelize()] = hash[prop];
    }

    // delegate to any type-specific normalizations
    return this._super(type, property, json);
  }

});

Have I understood it correct that I need to copy this same block now for every model that requires the _id as primary key ? Is there no longer a way to specify this once for the whole application ?

like image 969
cyclomarc Avatar asked Sep 01 '13 17:09

cyclomarc


1 Answers

Since the code seams to be type agnostic, why you don't just create your custom serializer that your models can extend from, something like:

App.Serializer = DS.RESTSerializer.extend({

  normalize: function (type, hash, property) {
    // property will be "post" for the post and "comments" for the
    // comments (the name in the payload)

    // normalize the `_id`
    var json = { id: hash._id };
    delete hash._id;

    // normalize the underscored properties
    for (var prop in hash) {
      json[prop.camelize()] = hash[prop];
    }

    // delegate to any type-specific normalizations
    return this._super(type, json, property);
  }

});

And then use App.Serializer for all your models:

App.AuthorSerializer = App.Serializer.extend();
App.PostSerializer = App.Serializer.extend();
...

Hope it helps.

like image 140
intuitivepixel Avatar answered Oct 01 '22 10:10

intuitivepixel