apollographql / apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
Other
130 stars 7 forks source link

Add cache eviction of a query via query DocumentNode #412

Open DanielRose opened 11 months ago

DanielRose commented 11 months ago

With the cache eviction of v3, it is possible to delete data from the cache. This includes queries, which was asked for in https://github.com/apollographql/apollo-feature-requests/issues/29 and https://github.com/apollographql/apollo-client/issues/6795, for example.

To evict a query, you need to know the fieldName and args of the query. Aside: passing in only the fieldName will evict the query for all args.

However in many cases, the code is using DocumentNode for the queries, together with variables. This can result in mismatches, because

  1. The DocumentNode could have multiple query fields
  2. The variables of the document might not match the arguments of the query

An example of this could be:

const MyTodoQuery = gql`
  query GetTodoData($onlyCompleted: Boolean!) {
    todos(filter: { completed: $onlyCompleted }) {
      id
      text
      completed
    }

    todoCategories {
      id
      name
    }
  }
`;

To evict the first query, you need to run one of the following, both of which require detailed knowledge of how the actual query is run.

const queryVariables = { onlyCompleted: true };

cache.evict({ fieldName: "todos", args: { filter: { completed: queryVariables.onlyCompleted } } });
cache.evict({ fieldName: `todos({"filter":{"completed":${queryVariables.onlyCompleted}"}})` });

When reading or writing queries to the cache, there are methods to specify the DocumentNode and variables directly, such as cache.writeQuery() and cache.readQuery(). These get the DocumentNode and variables, and internally convert that into the correct cache id.

My request would be to add a similar cache.evictQuery() method. It would combine the parameters of writeQuery and evict, ie. id, query, variables, broadcast.

DanielRose commented 11 months ago

Workaround/partial solution:

After tracing through the code of StoreWriter, I was able to figure out how to calculate the cache id using some of the internal(?) code of the cache's policies:

const MyTodoQuery = gql`
  query GetTodoData($onlyCompleted: Boolean!) {
    todos(filter: { completed: $onlyCompleted }) {
      id
      text
      completed
    }

    todoCategories {
      id
      name
    }
  }
`;
const queryVariables = { onlyCompleted: true };

const operationDefinition = getQueryDefinition(MyTodoQuery);
const queryTypename = cache.policies.rootTypenamesById['ROOT_QUERY'];
const cacheIds = operationDefinition.selectionSet.selections.filter(isField).map(fieldNode =>
  cache.policies.getStoreFieldName({
    typename: queryTypename,
    fieldName: fieldNode.name.value,
    field: fieldNode,
    variables: queryVariables,
  }),
);

cacheIds.forEach(cacheId => cache.evict({ fieldName: cacheId }));