Add check for internet connection before making http request.

This commit is contained in:
Spencer Ofwiti 2021-07-03 15:51:09 +03:00
parent beca2bf7f8
commit d74bebbbc3
6 changed files with 79 additions and 4 deletions

View File

@ -1,8 +1,6 @@
const apiUrls = [
'https://api.coindesk.com/v1/bpi/currentprice.json',
'https://dog.ceo/api/breeds/image/random',
'https://ipinfo.io/161.185.160.93/geo',
'https://randomuser.me/api/',
];
async function checkOnlineStatus(): Promise<boolean> {

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ConnectionInterceptor } from './connection.interceptor';
describe('ConnectionInterceptor', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [ConnectionInterceptor],
})
);
it('should be created', () => {
const interceptor: ConnectionInterceptor = TestBed.inject(ConnectionInterceptor);
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,42 @@
// Core imports
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
// Third party imports
import { Observable } from 'rxjs';
// Application imports
import { LoggingService } from '@app/_services/logging.service';
import { checkOnlineStatus } from '@app/_helpers';
/** Intercepts and handles of events from outgoing HTTP request. */
@Injectable()
export class ConnectionInterceptor implements HttpInterceptor {
/**
* Initialization of the connection interceptor.
*
* @param loggingService - A service that provides logging capabilities.
*/
constructor(private loggingService: LoggingService) {}
/**
* Intercepts HTTP requests.
*
* @param request - An outgoing HTTP request with an optional typed body.
* @param next - The next HTTP handler or the outgoing request dispatcher.
* @returns The forwarded request.
*/
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
checkOnlineStatus().then((online) => {
if (!online) {
this.loggingService.sendErrorLevelMessage('No internet connection on device!', this, {
error: `NetworkError when attempting to fetch resource ${request.url}.`,
});
return;
} else {
return next.handle(request);
}
});
return next.handle(request);
}
}

View File

@ -1,3 +1,4 @@
export * from '@app/_interceptors/connection.interceptor';
export * from '@app/_interceptors/error.interceptor';
export * from '@app/_interceptors/http-config.interceptor';
export * from '@app/_interceptors/logging.interceptor';

View File

@ -11,7 +11,12 @@ import { MatTableModule } from '@angular/material/table';
import { AuthGuard } from '@app/_guards';
import { LoggerModule } from 'ngx-logger';
import { environment } from '@src/environments/environment';
import { ErrorInterceptor, HttpConfigInterceptor, LoggingInterceptor } from '@app/_interceptors';
import {
ConnectionInterceptor,
ErrorInterceptor,
HttpConfigInterceptor,
LoggingInterceptor,
} from '@app/_interceptors';
import { MutablePgpKeyStore } from '@app/_pgp';
import { ServiceWorkerModule } from '@angular/service-worker';
@ -38,6 +43,7 @@ import { ServiceWorkerModule } from '@angular/service-worker';
MockBackendProvider,
GlobalErrorHandler,
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
{ provide: HTTP_INTERCEPTORS, useClass: ConnectionInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true },

View File

@ -1,4 +1,5 @@
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
@ -31,7 +32,7 @@ import { AccountDetails, Transaction } from '@app/_models';
styleUrls: ['./account-details.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AccountDetailsComponent implements OnInit {
export class AccountDetailsComponent implements OnInit, AfterViewInit {
transactionsDataSource: MatTableDataSource<any>;
transactionsDisplayedColumns: Array<string> = ['sender', 'recipient', 'value', 'created', 'type'];
transactionsDefaultPageSize: number = 10;
@ -194,6 +195,17 @@ export class AccountDetailsComponent implements OnInit {
});
}
ngAfterViewInit(): void {
if (this.userDataSource) {
this.userDataSource.paginator = this.userTablePaginator;
this.userDataSource.sort = this.userTableSort;
}
if (this.transactionsDataSource) {
this.transactionsDataSource.paginator = this.transactionTablePaginator;
this.transactionsDataSource.sort = this.transactionTableSort;
}
}
doTransactionFilter(value: string): void {
this.transactionsDataSource.filter = value.trim().toLocaleLowerCase();
}