Skip to content

Commit

Permalink
Allow getLast{Result,Error} to enforce variables equality.
Browse files Browse the repository at this point in the history
I might prefer the default behavior to be reversed (variables must match
by default), but these are `public` methods of `ObservableQuery`, so we
should be careful to preserve the same behavior when `getLastResult` or
`getLastError` are called with no arguments.
  • Loading branch information
benjamn committed Aug 13, 2021
1 parent 5bf41f0 commit 6cc1433
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions src/core/ObservableQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ export interface UpdateQueryOptions<TVariables> {

let warnedAboutUpdateQuery = false;

interface Last<TData, TVars> {
result: ApolloQueryResult<TData>;
variables: TVars;
error?: ApolloError;
}

export class ObservableQuery<
TData = any,
TVariables = OperationVariables
Expand All @@ -68,11 +74,7 @@ export class ObservableQuery<
private observers = new Set<Observer<ApolloQueryResult<TData>>>();
private subscriptions = new Set<ObservableSubscription>();

private last?: {
result: ApolloQueryResult<TData>;
variables: TVariables;
error?: ApolloError;
};
private last?: Last<TData, TVariables>;

private queryInfo: QueryInfo;

Expand Down Expand Up @@ -252,14 +254,26 @@ export class ObservableQuery<
return !this.last || !equal(this.last.result, newResult);
}

private getLast<K extends keyof Last<TData, TVariables>>(
key: K,
variablesMustMatch?: boolean,
) {
const last = this.last;
if (last &&
last[key] &&
(!variablesMustMatch || equal(last!.variables, this.variables))) {
return last[key];
}
}

// Returns the last result that observer.next was called with. This is not the same as
// getCurrentResult! If you're not sure which you need, then you probably need getCurrentResult.
public getLastResult(): ApolloQueryResult<TData> | undefined {
return this.last?.result;
public getLastResult(variablesMustMatch?: boolean): ApolloQueryResult<TData> | undefined {
return this.getLast("result", variablesMustMatch);
}

public getLastError(): ApolloError | undefined {
return this.last?.error;
public getLastError(variablesMustMatch?: boolean): ApolloError | undefined {
return this.getLast("error", variablesMustMatch);
}

public resetLastResults(): void {
Expand Down

0 comments on commit 6cc1433

Please sign in to comment.