How to differenciate models with the same name coming from two APIs?


#1

Hello,

We’re having a hard time finding the best way to handle conflicting models from two APIs. Both APIs use JSONAPI and provide the posts and comments endpoints.

Our Ember application needs to be able to use those two APIs on the same page. What would be the best approach?

We’ve tried creating a separate adapter for the second API but when the payload is parsed the records are stored in the first API’s posts :confused:

The application was developed using the first API api1.test.com/api/v1/posts and we now need to compare the posts from the second API api2.test.com/api/v2/posts.

Is there any way to completely encapsulate what comes from a specific API to avoid this kind of conflicts?

Thanks! :heart:


#2

This should be possible! First (and I think you may already doing this part), the models should have different names. Let’s say they are: post-type-1 and post-type-2.

Then, create serializers for each of those types. In your serializers/post-type-1.js, you can use the modelNameFromPayloadType hook to convert the post type into post-type-1 (and payloadTypeFromModelName for the opposite effect:

// app/serializers/post-type-1.js
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  modelNameFromPayloadType(payloadType) {
    return `${payloadType}-type-1`
  },
  payloadTypeFromModelName(modelName) {
    return modelName.replace('-type-1', '');
  }
});

(Then, of course, you’ll want to do the same thing for the post-type-2)

Hope this helps!