mzabriskie
mzabriskie

Reputation: 542

Using Ember Data with non standard REST API

I am trying to hook up Ember Data to work with an existing REST API. The problem that I am running into is that the REST implementation does not conform to how Ember Data expects things to be done. I have scoured the web for documentation that would suggest how to make things work, but short of writing my own DS.Adapter implementation I am at a loss.

Here is what my request looks like:

/api/user/12345

which provides the following response:

{
    data: {
        ID: '12345',
        firstName: 'Fred',
        lastName: 'Flintstone',
        emailAddr: '[email protected]'
    }
}

Ember expects "data" to be "user". Unfortunately I cannot easily change the API. Any suggestions?

Thanks

Upvotes: 1

Views: 614

Answers (1)

intuitivepixel
intuitivepixel

Reputation: 23322

One way I can think of you could achieve this, would be by creating your own serializer and override the extract function:

App.RESTSerializer = DS.RESTSerializer.extend({
  extract: function(loader, json, type, record) {
    var root = 'data';

    if (json[root]) {
      if (record) { loader.updateId(record, json[root]); }
      this.extractRecordRepresentation(loader, type, json[root]);
    }
  }
});

App.Store = DS.Store.extend({
  adapter: DS.RESTAdapter.extend({
    serializer: App.RESTSerializer.create()
  })
});

Please note that this modification assumes that the content of your request will always be under the data key of your JSON.

Also worth mentioning is that the original extract method has two lines which are not included in the example:

 this.sideload(loader, type, json, root);
 this.extractMeta(loader, type, json);

this makes you loose side loading functionality and metadata extraction. I hope loosing this functionality is not a show stopper for your use case.

Hope it helps.

Upvotes: 2

Related Questions