Search code examples
node.jsgraphqlrelayapollostack

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?


Solution

  • 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.