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

2

8

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?

Stovall answered 4/12, 2016 at 7:58 Comment(0)
M
11

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.

Magnus answered 8/12, 2016 at 16:11 Comment(0)
M
3

In apollo-client v2, You must pass dataIdFromObject to InMemoryCache instance instead.

import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import ApolloClient from 'apollo-client';

const client = new ApolloClient({
  link: new HttpLink(),
  cache: new InMemoryCache({
    dataIdFromObject: object => object.id,
  }),
});
Mcfadden answered 11/7, 2018 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.