Alberto Rico
Alberto Rico

Reputation: 395

Adapter that converges two API sources into one model

Let's say I have a JSON API where I can access two models: cats and dogs. However, on my Ember application I only have one model: animals.

Although every time I save() an animal, it's POSTed to the API as a cat, if I receive a dog linked in any other model it should be locally stored as an animal by ember-data.

What would be the most coherent way to achieve this? Thank you!

Upvotes: 1

Views: 69

Answers (2)

Alberto Rico
Alberto Rico

Reputation: 395

Fixed. For future reference, it is possible to create an alias to a model, extending the ApplicationSerializer (in this case, our model is animal, and although it had an adapter that used the cat model in the API, the dog model needed to be parsed as an animal as well):

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
  typeForRoot: function(root) {
    if (root == 'dog' || root == 'dogs') { root = 'animal'; }
    return this._super(root);
  }
);

Upvotes: 1

Oren Hizkiya
Oren Hizkiya

Reputation: 4434

You should be able to achieve what you want by customizing the REST adapter. Specifically, look into overriding the buildURL method to detect the type of the record passed and to construct the URL to be passed based on logic that determines whether this particular model should be persisted to the cats endpoint or dogs endpoint.

Upvotes: 0

Related Questions