Skip to content

Commit

Permalink
Schedule QueryInfo#notify whenever queryInfo becomes dirty.
Browse files Browse the repository at this point in the history
This is a big deal because it means we no longer have to remember to call
broadcastQueries after updating watched queries in the cache.
  • Loading branch information
benjamn committed Mar 11, 2020
1 parent 20ba25b commit 9148394
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ const { hasOwnProperty } = Object.prototype;

export class QueryInfo {
listeners = new Set<QueryListener>();
dirty = false;
document: DocumentNode | null = null;
lastRequestId = 1;
observableQuery: ObservableQuery<any> | null = null;
Expand All @@ -68,13 +67,31 @@ export class QueryInfo {
return Object.assign(this, info);
}

private dirty: boolean = false;

public isDirty() {
return this.dirty;
}

public setDirty(): this {
if (!this.dirty) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(() => this.notify(), 0);
}
}
return this;
}

private notifyTimeout?: ReturnType<typeof setTimeout>;

private diff: Cache.DiffResult<any> | null = null;

setDiff(diff: Cache.DiffResult<any> | null) {
const oldDiff = this.diff;
this.diff = diff;
if (!this.dirty && !equal(diff, oldDiff)) {
this.dirty = true;
// TODO Inform this.listeners.
this.setDirty();
}
}

Expand Down Expand Up @@ -114,6 +131,11 @@ export class QueryInfo {
}

notify() {
if (this.notifyTimeout) {
clearTimeout(this.notifyTimeout);
this.notifyTimeout = void 0;
}

if (this.shouldNotify() && this.getDiff()) {
this.listeners.forEach(listener => listener(this));
this.dirty = false;
Expand Down Expand Up @@ -540,9 +562,9 @@ export class QueryManager<TStore> {
this.getQuery(queryId).init({
document: query,
lastRequestId: requestId,
dirty: true,
}).updateWatch(options);

this.dirty(queryId);
this.dirty(fetchMoreForQueryId);

this.qsInitQuery({
Expand Down Expand Up @@ -1206,7 +1228,7 @@ export class QueryManager<TStore> {
fetchPolicy === 'no-cache' ||
fetchPolicy === 'network-only';

if (isNetworkOnly || info.dirty) {
if (isNetworkOnly || info.isDirty()) {
const diff = info.getDiff();
if (diff?.complete) {
return { data: diff.result, partial: false };
Expand Down Expand Up @@ -1463,12 +1485,9 @@ export class QueryManager<TStore> {
return this.queries.get(queryId);
}

private dirty(
queryId: string | undefined,
dirty = true,
) {
private dirty(queryId?: string) {
if (queryId) {
this.getQuery(queryId).dirty = dirty;
this.getQuery(queryId).setDirty();
}
}

Expand Down

0 comments on commit 9148394

Please sign in to comment.