Tom
Tom

Reputation: 12659

Apollo link middleware to update and retry request with non error response

I am trying to write apollo link middleware which will retry certain requests using a value returned in the payload of the initial failure. I can see the request is being correctly retried, but the middleware is not correctly returning the retry response in the apollo link chain. I can see when adding a logging middleware just before the below, nothing is returned although the request is successfully made.

How would I get this middleware to correctly return the retried result?

export const handlerVersionMismatch: ApolloLink = new ApolloLink(
  (operation: Operation, forward: NextLink) => {
    return new Observable<FetchResult>((observer) => {
      let retry = true;

      const handleResponse = (response: FetchResult) => {
        if (retry && handleVersionMismatch(response)) {
          const newVersion = response.data?.cart?.version;
          operation.variables.version = newVersion;
          retry = false;
          forward(operation).subscribe(observer);
        } else {
          observer.next(response);
        }
      };

      const subscription = forward(operation).subscribe({
        next: handleResponse,
        error: (err) => observer.error(err),
        complete: () => observer.complete(),
      });

      // Clean up the subscription when observer is completed or errored
      return () => {
        subscription.unsubscribe();
      };
    });
  },
);

Upvotes: 1

Views: 153

Answers (1)

Marco Merola
Marco Merola

Reputation: 879

There might be an issue with how the retry response is returned in the Apollo Link chain.

...
const handleResponse = (response: FetchResult) => {
        if (retry && handleVersionMismatch(response)) {
          const newVersion = response.data?.cart?.version;
          operation.variables.version = newVersion;
          retry = false;
          return forward(operation).subscribe(observer); // Add return
        } else {
          observer.next(response);
        }
      };
...

Upvotes: 0

Related Questions