Multiple adapters for specific models?


#1

Hello,

I am developing an Ember App with REST adapter. There are two parts of the app - the public part and the administration part. So far I created the public part. So I created application adapter, models and everything works great. Now I am dealing with the administration part and there’s a little struggle. The administration part uses almost the same models as the public part however it adds more data to the models and uses different API.

I read the manual and I have no clue, how to realize this. For example I have a model user and task in the public interface. The user can be obtained on /users endpoint and task can be obtained on the /tasks endpoint. For admin interface I have also user model, which has now more fields, and can be obtained on /admin/user endpoint and similary the tasks.

How to solve this? How to tell the store in which adapter it should use?


#2

I don’t think multiple adapters can be applied to one model currently, correct me if wrong.

In other ways, when you issue a query you can find out where you are, I mean wether you’re in user route or admin.user route, then you can extract this information out as a query parameter.

In adapter, you can override corresponding method (eg. Adapter#query), fire different ajax request depending on the information you passed in here.


#3

You can try creating two models: Model and PrivilegedModel, with PrivilegedModel extending Model.

Now you’re allowed to have 2 adapters, and PrivilegedModel can be passed to anywhere that’s expecting a Model.


#4

Thank you for your responses. I thought I could create another model, however the API I am working with is fixed and cannot be changed - in the JSON response the model is named Model instead of PrivilegedModel. Or is there a way how to tell the REST adapter to “convert the names”? So I could do store.findAll(“PriviledgedModel”), the response containes “Models” field and the adapter is happy with it?

To nightire: I looked at the DS.Adapter and I think overring the query method is quite complicated and I am not sure how to achieve saving in that way.


#5

This would be a great place to use a serializer for the PrivilegedModel. Using the normalize{TYPE}Response hooks, you can change the type of the model from your payload.

// privileged-model/serializer.js
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
    payload.data.forEach(model => {
      model.type = 'privileged-model';
    });
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

Hope this helps!