Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements to options.nextFetchPolicy. #6893

Merged
merged 4 commits into from
Aug 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
- Check structural equality of diff results in `QueryInfo#setDiff` instead of reference equality. <br/>
[@benjamn](https://github.com/benjamn) in [#6891](https://github.com/apollographql/apollo-client/pull/6891)

- Use `options.nextFetchPolicy` internally to restore original `FetchPolicy` after polling with `fetchPolicy: "network-only"`, so that polling does not interfere with normal query watching. <br/>
[@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)

## Improvements

- Substantially improve type inference for data and variables types using `TypedDocumentNode<Data, Variables>` type instead of `DocumentNode`. <br/>
[@dotansimha](https://github.com/dotansimha) in [#6720](https://github.com/apollographql/apollo-client/pull/6720)

- Allow `options.nextFetchPolicy` to be a function that takes the current `FetchPolicy` and returns a new (or the same) `FetchPolicy`, making `nextFetchPolicy` more suitable for global use in `defaultOptions.watchQuery`. <br/>
[@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)

- Disable feud-stopping logic after any cache eviction. <br/>
[@benjamn](https://github.com/benjamn) in [#6817](https://github.com/apollographql/apollo-client/pull/6817)

Expand Down
90 changes: 90 additions & 0 deletions src/__tests__/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3164,6 +3164,96 @@ describe('@connection', () => {
});
});

itAsync('allows setting nextFetchPolicy in defaultOptions', (resolve, reject) => {
let networkCounter = 0;
let nextFetchPolicyCallCount = 0;

const client = new ApolloClient({
link: new ApolloLink(operation => new Observable(observer => {
observer.next({
data: {
count: networkCounter++,
},
});
observer.complete();
})),

cache: new InMemoryCache,

defaultOptions: {
watchQuery: {
nextFetchPolicy(fetchPolicy) {
expect(++nextFetchPolicyCallCount).toBe(1);
expect(this.query).toBe(query);
expect(fetchPolicy).toBe("cache-first");
// Usually options.nextFetchPolicy applies only once, but a
// nextFetchPolicy function can set this.nextFetchPolicy
// again to perform an additional transition.
this.nextFetchPolicy = fetchPolicy => {
++nextFetchPolicyCallCount;
expect(fetchPolicy).toBe("cache-and-network");
return "cache-first";
};
return "cache-and-network";
},
},
},
});

const query = gql`
query {
count
}
`;

client.writeQuery({
query,
data: {
count: "initial",
},
});

const obs = client.watchQuery({ query });

subscribeAndCount(reject, obs, (handleCount, result) => {
if (handleCount === 1) {
expect(nextFetchPolicyCallCount).toBe(1);
expect(result.data).toEqual({ count: "initial" });
// Refetching makes a copy of the current options, which
// includes options.nextFetchPolicy, so the inner
// nextFetchPolicy function ends up getting called twice.
obs.refetch();
} else if (handleCount === 2) {
expect(result.data).toEqual({ count: "initial" });
expect(nextFetchPolicyCallCount).toBe(2);
} else if (handleCount === 3) {
expect(result.data).toEqual({ count: 0 });
expect(nextFetchPolicyCallCount).toBe(2);
client.writeQuery({
query,
data: {
count: "secondary",
},
});
} else if (handleCount === 4) {
expect(result.data).toEqual({ count: "secondary" });
expect(nextFetchPolicyCallCount).toBe(3);
} else if (handleCount === 5) {
expect(result.data).toEqual({ count: 1 });
expect(nextFetchPolicyCallCount).toBe(3);
client.cache.evict({ fieldName: "count" });
} else if (handleCount === 6) {
expect(result.data).toEqual({ count: 2 });
expect(nextFetchPolicyCallCount).toBe(3);
expect(obs.options.fetchPolicy).toBe("cache-first");
expect(obs.options.nextFetchPolicy).toBeUndefined();
setTimeout(resolve, 50);
} else {
reject("too many results");
}
});
});

itAsync('allows setting default options for query', (resolve, reject) => {
const errors = [{ message: 'failure', name: 'failure' }];
const link = mockSingleLink({
Expand Down
18 changes: 12 additions & 6 deletions src/core/ObservableQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export class ObservableQuery<
fetchPolicy !== 'cache-and-network') {
reobserveOptions.fetchPolicy = 'network-only';
// Go back to the original options.fetchPolicy after this refetch.
reobserveOptions.nextFetchPolicy = fetchPolicy;
reobserveOptions.nextFetchPolicy = fetchPolicy || "cache-first";
}

if (variables && !equal(this.options.variables, variables)) {
Expand Down Expand Up @@ -436,16 +436,22 @@ once, rather than every time you call fetchMore.`);
}

let { fetchPolicy = 'cache-first' } = this.options;
const reobserveOptions: Partial<WatchQueryOptions<TVariables, TData>> = {
fetchPolicy,
variables,
};

if (fetchPolicy !== 'cache-first' &&
fetchPolicy !== 'no-cache' &&
fetchPolicy !== 'network-only') {
fetchPolicy = 'cache-and-network';
reobserveOptions.fetchPolicy = 'cache-and-network';
reobserveOptions.nextFetchPolicy = fetchPolicy;
}

return this.reobserve({
fetchPolicy,
variables,
}, NetworkStatus.setVariables);
return this.reobserve(
reobserveOptions,
NetworkStatus.setVariables,
);
}

public updateQuery<TVars = TVariables>(
Expand Down
14 changes: 10 additions & 4 deletions src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -909,7 +909,13 @@ export class QueryManager<TStore> {
concast.cleanup(() => {
this.fetchCancelFns.delete(queryId);

if (options.nextFetchPolicy) {
const { nextFetchPolicy } = options;
if (nextFetchPolicy) {
// The options.nextFetchPolicy transition should happen only once,
// but it should be possible for a nextFetchPolicy function to set
// this.nextFetchPolicy to perform an additional transition.
options.nextFetchPolicy = void 0;

// When someone chooses cache-and-network or network-only as their
// initial FetchPolicy, they often do not want future cache updates to
// trigger unconditional network requests, which is what repeatedly
Expand All @@ -920,9 +926,9 @@ export class QueryManager<TStore> {
// The options.nextFetchPolicy option provides an easy way to update
// options.fetchPolicy after the intial network request, without
// having to call observableQuery.setOptions.
options.fetchPolicy = options.nextFetchPolicy;
// The options.nextFetchPolicy transition should happen only once.
options.nextFetchPolicy = void 0;
options.fetchPolicy = typeof nextFetchPolicy === "function"
? nextFetchPolicy.call(options, options.fetchPolicy || "cache-first")
: nextFetchPolicy;
}
});

Expand Down
1 change: 1 addition & 0 deletions src/core/Reobserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export class Reobserver<TData, TVars> {
if (this.shouldFetch && this.shouldFetch()) {
this.reobserve({
fetchPolicy: "network-only",
nextFetchPolicy: this.options.fetchPolicy || "cache-first",
}, NetworkStatus.poll).then(poll, poll);
} else {
poll();
Expand Down
5 changes: 4 additions & 1 deletion src/core/watchQueryOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ export interface WatchQueryOptions<TVariables = OperationVariables, TData = any>
/**
* Specifies the {@link FetchPolicy} to be used after this query has completed.
*/
nextFetchPolicy?: WatchQueryFetchPolicy;
nextFetchPolicy?: WatchQueryFetchPolicy | ((
this: WatchQueryOptions<TVariables, TData>,
lastFetchPolicy: WatchQueryFetchPolicy,
) => WatchQueryFetchPolicy);
}

export interface FetchMoreQueryOptions<TVariables, K extends keyof TVariables, TData = any> {
Expand Down