Previous request to then execute another request at the angle

Asked

Viewed 139 times

0

After the user is logged in to my application, all the requests he performs must first hit an API that will validate if the plan is in agreement.

Is there any way to standardize the requests so that always make this previous request and only then perform the requested request if the plan is in agreement? Or I need to file a requisition?

The Http injector would serve for this?

Thank you

1 answer

0


You need to use an Httpinterceptor.

For that you create a service of this kind:

@Injector()
export class RequestInterceptorService implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // adiciona o token desta forma
        // neste exemplo o token, quando existe, está guardado na localstorage
        if (localStorage.getItem('accessToken')) {
            request = request.clone({
                setHeaders: {
                    Authorization: 'Bearer ' + localStorage.getItem('accessToken')
                }
            });
        }


         return next.handle(request).pipe(
            tap(
              event => { },
              error => {
                this.handleErrors(error);
              }
            ),
            finalize(() => { })
        );
    }

    private handleErrors(err: HttpErrorResponse) {
        let errorMessage: string;
        if (err.status === 0) {
            errorMessage = 'Sem ligação à internet';
        } else if (err.status === 401) { // O token expirou ou nem foi enviado. Fazer novamente autenticação. 
            this.router.navigate(['/login']);
        } else { // ocorreu outro erro. Mostrar mensagem ao utilizador
            errorMessage = err.error.message;
        }

        if(errorMessage) {
            // mostrar mensagem em modal, por exemplo
        }
    }
}

And you add the service to HTTP_INTERCEPTORS providers:

@NgModule({
    declarations: [
        // ...
    ],
    imports: [
        // ...
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: RequestInterceptorService,
            multi: true,
        }
    ],
})

export class AppModule { }
  • This is already what I do in my Interceptor currently, I need to make a previous http request to see if the token is still valid, and only if it is valid to put it in the next request

  • 1

    @Renatoveronese This will slow down the application. The best way is to let the server respond that the token has expired. Updated response code for this scenario.

  • I know, but my boss wants it that way, I already explained that this is done in the backend through the token but he wants one more validation

  • @Renatoveronese And explained that for every request made, you will always have an extra to validate the token, what will make the site/webapp slower and double the load on the server? The only thing that made sense to me was validating the expiration date to token. If you’re using something like JWT, in the token itself you have that information embedded. https://gist.github.com/soulmachine/b368ce7292ddd7f91c15accccc02b8df

Browser other questions tagged

You are not signed in. Login or sign up in order to post.