mercredi 12 septembre 2018

Ember.js two API's same resource name

Desired outcome: To have two models available; "bc-theme" and "ra-theme" in ember pulled from two different API's that use the resource name "theme".

I have a simple way of serializing the model name for one "rename" but have not found a way to determine the rename based on what API it's requested from and thus be able to rename appropriately. As you can see from the provided code, the mappings will fail if I introduce another "theme" because their will be muliple of the same keys on the mapping for normalization.

Without the extra theme the mappings work as expected.

Is there some way to see what adapter is being used in the serializer? Or since it's being request by an ember findRecord and via relationships could the theme "type" be determined some other way on each request?

The backends are written in Ruby on Rails and can be modified as well, but it seems like ember should be the one to handle the differences since the API's are independent of one another.

// adapters/ra-theme.js
import RaAdapter from './ra';

export default RaAdapter.extend({
  pathForType() {
    return this._super('themes');
  }
});

// adapters/bc-theme.js
import bcAdapter from './bc';

export default bcAdapter.extend({
  pathForType() {
    return this._super('themes');
  }
});


// serializers/application.js
import DS from 'ember-data';

const keysMappingForSerialization = {
  'bc-theme': 'theme',
  ...
};
const keysMappingForNormalization = {
  'theme': 'bc-theme',
  ...
};

export default DS.JSONAPISerializer.extend({
  payloadKeyFromModelName(key) {
    if (keysMappingForSerialization[key]) {
      return this._super(keysMappingForSerialization[key]);
    } else {
      return this._super(...arguments);
    }
  },
  modelNameFromPayloadKey(modelName) {
    if (keysMappingForNormalization[modelName]) {
      return this._super(keysMappingForNormalization[modelName]);
    } else {
      return this._super(...arguments);
    }
  }

});

// serializers/bc-theme-group.js
import ApplicationSerializer from './application';

const keysForRelationshipsMapping = {
  'bcThemes': 'themes'
};

export default ApplicationSerializer.extend({
  keyForRelationship(key) {
    if (keysForRelationshipsMapping[key]) {
      return this._super(keysForRelationshipsMapping[key]);
    } else {
      return this._super(...arguments);
    }
  }
});

// serializers/bc-theme.js
import ApplicationSerializer from './application';

const keysForRelationshipsMapping = {
  'bcThemeGroups': 'themeGroups'
};

export default ApplicationSerializer.extend({
  keyForRelationship(key) {
    if (keysForRelationshipsMapping[key]) {
      return this._super(keysForRelationshipsMapping[key]);
    } else {
      return this._super(...arguments);
    }
  }
});



Aucun commentaire:

Enregistrer un commentaire