Manu Benjamin
Manu Benjamin

Reputation: 997

Ember - Custom adapter and serializer for multiple models

I am using RESTAdapter and RESTSerializer for integrating rest service in my ember project. I am able to do the rest service operation with the default ApplicationAdapter(Extend RESTAdapter) and I am able to create custom adapter for specific models.

I want to create a custom adapter which can be used for some specific set of models.

example,

//Application adapter extends RESTAdapter

var LookupAdapter = ApplicationAdapter.extend({
   host: Properties.LookupServiceHost,
   namespace : Properties.LookupServiceNamespace,
});

export default LookupAdapter;

I have some models like country, language etc. For fetching and populating data in data store, now I am using separate adapter, serializer(for handling request, response) for each model. I want those specific models to be worked with LookupAdapter. Can we assign this adapter to model anyway so that these models will use the LookupAdapter/LookupSerializer?

Is there a way to tell model that your Adapter is LookupAdapter?

Upvotes: 1

Views: 994

Answers (1)

Timm
Timm

Reputation: 1015

You could create Adapters and Serializers for every model and import your LookupAdapter / -Serializer and extend from it. Non tested code ahead:

// In file ../adapters/country.js
import LookupAdapter from '../adapters/lookup';
export default LookupAdapter.extend({});

I think you could even omit the .extend({}).

EDIT:

If you do not want to create an adapter and serializer for each model you could implement your own DS.Store. DS.Store provides these methods:

  • adapterFor
  • serializerFor

You could write a mapping table, which maps the modelName to an adapter you specify.

In addition, the ember.js source code says, that when no adapter is found ApplicationAdapter is used instead.

EDIT 2:

You could do something like this:

app/mappings/adapters.js:

export default {
  'country': 'lookup',
  'city': 'lookup'
}

app/stores/application.js:

import adaptersMapping from '../mappings/adapters';

export default DS.Store.extend({
  adapterFor(modelName) {
    if(adaptersMapping[modelName]) {
      return this._super(adaptersMapping[modelName]);
    }
    return this._super(modelName);
  }
});

Upvotes: 2

Related Questions