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


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 and we now need to compare the posts from the second API

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

Thanks! :heart:

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!

1 Like

Hi @Spencer_Price and thanks for your answer. That’s actually what we did but it still conflicted when receiving data from the server because it was not calling the modelNameFromPayloadType.

We did not have post-type-1 and post-type-2 but rather post and post-type-2. Since the API was responding with type="posts" it was selecting the Post model directly.

We negociated to avoid the conflict between resources so far so we won’t push for a solution today. I’ll come back to this issue once we’re forced to work on it and I’ll keep you posted.

I’d think you could do this in the handleResponse method of the adapter. Since the adapter is making the request to begin with it should be “aware” of which model it is for, and then the server response can be “re-typed” in the adapter before it hits the serializers. So in handleResponse you change the type from “posts” to “post-type-2” if it’s in that adapter before passing it along to the serializer layer.

@dknutsen that’s what we did too but then starts the fun of having to also change any relationships that the payload may contain. During our proof of concept we ended-up with an adapter per model with the type change and the handling of every conflicting relationship. That seems like a lot for just a “simple” problem.