Why is the purpose of "extraRootIds" in apollo cache

Viewed 190

I work on a projet: React / Apollo Client. When i want to update cache after mutation (in case of adding new object) i see in apollo developper tools a element called 'extraRootIds' enter image description here

create({
                variables: { object: film },
                update: (cache, { data }) => {
                    const entity = data.insert_film_one;
                    cache.modify({
                        fields: {
                            search_film: (existingEntityRefs, { readField }) => {
                                const newEntityRef = cache.writeFragment({
                                    id: 'film:{"film_id":' + entity.film_id + '}',
                                    data: entity,
                                    fragment: FILM_CREATE_FIELDS
                                });
                                return [...existingEntityRefs, newEntityRef];
                            }
                        }
                    });
                }
            });

Everything seems to be ok but i wonder if this extrarootIds is normal.

Thanks ;)

2 Answers

I'm not entirely sure myself since I am somewhat of a beginner Apollo Client user and I couldn't find explicit documentation for it. Searching through the source code though you can see where it is defined:

public extract(): NormalizedCacheObject {
const obj = this.toObject();
const extraRootIds: string[] = [];
this.getRootIdSet().forEach(id => {
  if (!hasOwn.call(this.policies.rootTypenamesById, id)) {
    extraRootIds.push(id);
  }
});
if (extraRootIds.length) {
  obj.__META = { extraRootIds: extraRootIds.sort() };
}
return obj;

}

https://github.com/apollographql/apollo-client/blob/cbcf951256b22553bdb065dfa0d32c0a4ca804d3/src/cache/inmemory/entityStore.ts#L276

where getRootIdSet() returns:

a Set of all the ID strings that have been retained by this layer/root and any layers/roots beneath it.

So there doesn't seem to be any discernment about what shows up in the Meta storage of the cache. We should probably just assume they are saving every newly altered cache ID there for their own internal use.

From the code comments:

Well-known singleton IDs like ROOT_QUERY and ROOT_MUTATION are always considered to be root IDs during cache.gc garbage collection, but other IDs can become roots if they are written directly with cache.writeFragment or retained explicitly with cache.retain. When such IDs exist, we include them in the __META section so that they can survive cache.{extract,restore}.

https://github.com/apollographql/apollo-client/blob/d9a1039d36801d450a79cb56870f0a351044254b/src/cache/inmemory/types.ts#L91

Related