Skip to content

Instantly share code, notes, and snippets.

@duxor
Last active January 6, 2020 18:56
Show Gist options
  • Select an option

  • Save duxor/5a1f42a99b5bdb27005564da066ab161 to your computer and use it in GitHub Desktop.

Select an option

Save duxor/5a1f42a99b5bdb27005564da066ab161 to your computer and use it in GitHub Desktop.
Angular API interceptor with request/response time duration and ngrx selector.
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {environment} from '@env/environment';
import {Store} from '@ngrx/store';
import {Observable, throwError} from 'rxjs';
import {catchError, finalize, first, flatMap} from 'rxjs/operators';
import {AppState} from '@store/app.states';
import {TokenStorageService} from '@coreServices/user/token-storage.service';
import {getTokensState} from '@store/selectors/auth.selector';
import {Tokens} from '@models/user/tokens';
@Injectable({
providedIn: 'root'
})
export class ApiInterceptor implements HttpInterceptor {
constructor(private store: Store<AppState>,
private router: Router) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.store.select(getTokensState)
.pipe(
first(),
flatMap((tokens: Tokens) => {
if (request.url.substring(request.url.length - 5) !== '.json') {
request = request.clone({
url: `${environment.apiUrl}${request.url}`
});
}
const token = tokens ? tokens.access_token : false;
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
console.log('=============================');
console.log(request.url);
const startTime = new Date();
console.log(`Start Time: ${startTime}`);
return next.handle(request)
.pipe(
finalize(() => {
const endTime = new Date();
console.log(`End Time: ${endTime}`);
const durationMilliseconds = endTime.getTime() - startTime.getTime();
const durationSeconds = durationMilliseconds / 1000;
console.log(`Duration: ${durationMilliseconds} milliseconds = ${durationSeconds} seconds`);
}),
catchError(err => {
if (token) {
if (err.status === 401) {
this.router.navigate(['/auth/logout']);
return throwError(err);
}
}
return throwError(err);
})
);
}),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment