Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Apollo Stack support global object identification like the node interface of Relay?

I am very new in both Apollo Stack and Relay. I am trying to choose between them to invest my time. After finish reading the book Learning GraphQL and Relay, I turned to Apollo to learn what it has to offer but right now there are not much resources in the internet.

I have this question recently but unable to find the answer: Does Apollo support global object identification like Relay does with the node interface? if not, does it have any alternative solution to support global object identification?

like image 767
kkkkkkk Avatar asked Dec 04 '16 07:12

kkkkkkk


1 Answers

Yes!

The way it currently works (version 0.5 of apollo-client) is with the dataIdFromObject function that the ApolloClient constructor accepts.

If all nodes got an id field and they are unique across all nodes (at Graphcool for example, we generate unique ids with this library):

import ApolloClient from 'apollo-client';

const client = new ApolloClient({
  dataIdFromObject: o => o.id
});

You have to make sure to include the id field in every query you want to be normalized.

If your ids are only unique per type, you can combine them with __typename to create unique identifiers:

const client = new ApolloClient({
  dataIdFromObject: (result) => {
    if (result.id && result.__typename) {
      return result.__typename + result.id;
    }

    // Make sure to return null if this object doesn't have an ID
    return null;
  },
});

The code is taken from the official Apollo documentation.

like image 149
marktani Avatar answered Oct 08 '22 17:10

marktani