0
\$\begingroup\$

How can the following method be flattened? I tried to pipe all the operators to the first pipe (from(this.fireAuth.currentUser)) but I lost access to the previous variables. It's an Angular HTTP interceptor that adds a Bearer Token when the user has logged in, the chain should continue as usual when the user has not logged in yet.

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken()).pipe(
          switchMap(token => {
            if (isApiUrl) request = this.addToken(request, token);
            return next.handle(request).pipe(
              catchError(error => {
                if ( isApiUrl && token && error instanceof HttpErrorResponse && error.status === 403) {
                  return this.handle403Error(request, next);
                }
                else{
                  return throwError(error); 
                }
              })
            );
          })
        )
      })
    );
  }

Piping to the first observable... I have no access to the token var in the catchError block 😥

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken());
      }),
      filter<string>(x => typeof(x) === "string"), //x can be string to HttpEvent<any>
      switchMap(token => {
        if (isApiUrl) request = this.addToken(request, token);
        return next.handle(request)
      }),
      catchError(error => {
        if ( isApiUrl && error instanceof HttpErrorResponse && error.status === 403) {
          return this.handle403Error(request, next);
        }
        else{
          return throwError(error); 
        }
      })
    );
  }

I'm also wondering what's happening in the scenario where user is falsy, does it mean the request will be canceled because it does not pass the filter?

Thanks.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.