From 0ce75b2951781fdd369f6f62b6a89a8f700b7370 Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Sun, 21 Mar 2021 14:02:18 +0300 Subject: [PATCH] Scrap HttpWrapperService. --- src/app/_pgp/pgp-key-store.ts | 12 ++-- src/app/_services/auth.service.ts | 18 +++--- src/app/_services/block-sync.service.ts | 4 +- .../_services/http-wrapper.service.spec.ts | 16 ----- src/app/_services/http-wrapper.service.ts | 60 ------------------- src/app/_services/index.ts | 1 - src/app/_services/location.service.ts | 6 +- src/app/_services/token.service.ts | 6 +- src/app/_services/transaction.service.ts | 8 +-- src/app/_services/user.service.ts | 58 ++++++------------ src/app/app.component.ts | 2 +- .../account-details.component.ts | 4 +- src/app/pages/accounts/accounts.component.ts | 1 + src/app/pages/admin/admin.component.ts | 4 +- .../token-details/token-details.component.ts | 2 +- 15 files changed, 49 insertions(+), 153 deletions(-) delete mode 100644 src/app/_services/http-wrapper.service.spec.ts delete mode 100644 src/app/_services/http-wrapper.service.ts diff --git a/src/app/_pgp/pgp-key-store.ts b/src/app/_pgp/pgp-key-store.ts index 170be22..ed3938c 100644 --- a/src/app/_pgp/pgp-key-store.ts +++ b/src/app/_pgp/pgp-key-store.ts @@ -45,7 +45,7 @@ class MutablePgpKeyStore implements MutableKeyStore{ } importPublicKey(publicKey: any): void { - keyring.publicKeys.importKey(publicKey) + keyring.publicKeys.importKey(publicKey); } async importPrivateKey(privateKey: any): Promise { @@ -77,13 +77,9 @@ class MutablePgpKeyStore implements MutableKeyStore{ } async isValidKey(key): Promise { - // There is supposed to be an opengpg.readKey() method but I can't find it? - const _key = await openpgp.key.readArmored(key) - if (_key.err) { - return false - } else { - return true - } + // There is supposed to be an opengpg.readKey() method but I can't find it? + const _key = await openpgp.key.readArmored(key); + return !_key.err; } getFingerprint(): string { diff --git a/src/app/_services/auth.service.ts b/src/app/_services/auth.service.ts index bd907bd..80a9eb8 100644 --- a/src/app/_services/auth.service.ts +++ b/src/app/_services/auth.service.ts @@ -3,12 +3,11 @@ import { hobaParseChallengeHeader } from '@src/assets/js/hoba.js'; import { signChallenge } from '@src/assets/js/hoba-pgp.js'; import {environment} from '@src/environments/environment'; import {LoggingService} from '@app/_services/logging.service'; -import {HttpWrapperService} from '@app/_services/http-wrapper.service'; import {MutableKeyStore, MutablePgpKeyStore} from '@app/_pgp'; import {ErrorDialogService} from '@app/_services/error-dialog.service'; -import {catchError, first, tap} from 'rxjs/operators'; +import {tap} from 'rxjs/operators'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; -import { throwError } from 'rxjs'; +import {Observable, throwError} from 'rxjs'; @Injectable({ providedIn: 'root' @@ -20,7 +19,6 @@ export class AuthService { mutableKeyStore: MutableKeyStore = new MutablePgpKeyStore(); constructor( - private httpWrapperService: HttpWrapperService, private httpClient: HttpClient, private loggingService: LoggingService, private errorDialogService: ErrorDialogService @@ -125,7 +123,7 @@ export class AuthService { try { const isValidKeyCheck = await this.mutableKeyStore.isValidKey(privateKeyArmored) if (!isValidKeyCheck) { - throw Error("The private key is invalid") + throw Error('The private key is invalid'); } const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored); localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored); @@ -152,12 +150,12 @@ export class AuthService { return trustedUsers; } - getPublicKeys() { + getPublicKeys(): Observable { return this.httpClient.get(`${environment.publicKeysUrl}`, {responseType: 'text'}) .pipe(tap( data => { }, - error => { this.handleError(error, 'Unable to load trusted public keys.') } - )) + error => { this.handleError(error, 'Unable to load trusted public keys.'); } + )); } async getPrivateKeys(): Promise { @@ -166,8 +164,8 @@ export class AuthService { } } - // TODO this is from the docs and for reference. Move it somewhere better. - private handleError(error: HttpErrorResponse, customMessage: string) { + // TODO this is from the docs and for reference. Move it somewhere better. + private handleError(error: HttpErrorResponse, customMessage: string): Observable { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); diff --git a/src/app/_services/block-sync.service.ts b/src/app/_services/block-sync.service.ts index cc07386..d96d28f 100644 --- a/src/app/_services/block-sync.service.ts +++ b/src/app/_services/block-sync.service.ts @@ -59,11 +59,11 @@ export class BlockSyncService { }); if (address === null) { this.transactionService.getAllTransactions(offset, limit).pipe(first()).subscribe(res => { - this.fetcher(settings, res.body); + this.fetcher(settings, res); }); } else { this.transactionService.getAddressTransactions(address, offset, limit).pipe(first()).subscribe(res => { - this.fetcher(settings, res.body); + this.fetcher(settings, res); }); } } diff --git a/src/app/_services/http-wrapper.service.spec.ts b/src/app/_services/http-wrapper.service.spec.ts deleted file mode 100644 index b18b6b1..0000000 --- a/src/app/_services/http-wrapper.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { HttpWrapperService } from './http-wrapper.service'; - -describe('HttpWrapperService', () => { - let service: HttpWrapperService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(HttpWrapperService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/_services/http-wrapper.service.ts b/src/app/_services/http-wrapper.service.ts deleted file mode 100644 index 4987de9..0000000 --- a/src/app/_services/http-wrapper.service.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Injectable } from '@angular/core'; -import {HttpClient, HttpRequest} from '@angular/common/http'; -import {Observable} from 'rxjs'; -import * as moment from 'moment'; -import { Moment } from 'moment'; -import {LoggingService} from '@app/_services/logging.service'; - -@Injectable({ - providedIn: 'root' -}) -export class HttpWrapperService { - - constructor( - private http: HttpClient, - private loggingService: LoggingService, - ) { } - - get(url: string, options?: any): Observable { - return this.request('GET', url, null, options); - } - - post(url: string, body: any, options?: any): Observable { - return this.request('POST', url, body, options); - } - - put(url: string, body: any, options?: any): Observable { - return this.request('PUT', url, body, options); - } - - delete(url: string, options?: any): Observable { - return this.request('DELETE', url, null, options); - } - - private logTime(startMoment: Moment, url: string, method: string): void { - const requestDuration = moment().diff(startMoment, 'milliseconds'); - this.loggingService.sendInfoLevelMessage(`HTTP ${method}, URL: ${url}, Duration: ${requestDuration} ms`); - } - - private request(method: string, url: string, body?: any, options?: any): Observable { - this.loggingService.sendInfoLevelMessage(`Options: ${options}`); - return Observable.create((observer: any) => { - const requestBeginTime = moment(); - this.http.request(new HttpRequest(method, url, body, options)).subscribe((response) => { - this.loggingService.sendInfoLevelMessage(response); - this.logTime(requestBeginTime, `${url}`, method); - observer.next(response); - observer.complete(); - }, (error) => { - switch (error.status) { - case 403: - observer.complete(); - break; - default: - observer.error(error); - break; - } - }); - }); - } -} diff --git a/src/app/_services/index.ts b/src/app/_services/index.ts index ec50f32..6ded947 100644 --- a/src/app/_services/index.ts +++ b/src/app/_services/index.ts @@ -5,5 +5,4 @@ export * from '@app/_services/token.service'; export * from '@app/_services/block-sync.service'; export * from '@app/_services/location.service'; export * from '@app/_services/logging.service'; -export * from '@app/_services/http-wrapper.service'; export * from '@app/_services/error-dialog.service'; diff --git a/src/app/_services/location.service.ts b/src/app/_services/location.service.ts index cd163dc..834d02a 100644 --- a/src/app/_services/location.service.ts +++ b/src/app/_services/location.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; import {BehaviorSubject} from 'rxjs'; import {environment} from '@src/environments/environment'; import {first} from 'rxjs/operators'; -import {HttpWrapperService} from '@app/_services/http-wrapper.service'; +import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' @@ -13,10 +13,10 @@ export class LocationService { locationsSubject = this.locationsList.asObservable(); constructor( - private httpWrapperService: HttpWrapperService, + private httpClient: HttpClient, ) { } getLocations(): void { - this.httpWrapperService.get(`${environment.cicCacheUrl}/locations`).pipe(first()).subscribe(res => this.locationsList.next(res.body)); + this.httpClient.get(`${environment.cicCacheUrl}/locations`).pipe(first()).subscribe(res => this.locationsList.next(res)); } } diff --git a/src/app/_services/token.service.ts b/src/app/_services/token.service.ts index 8dc81ce..2924f53 100644 --- a/src/app/_services/token.service.ts +++ b/src/app/_services/token.service.ts @@ -4,8 +4,8 @@ import {BehaviorSubject, Observable} from 'rxjs'; import {HttpGetter} from '@app/_helpers'; import {CICRegistry} from 'cic-client'; import Web3 from 'web3'; -import {HttpWrapperService} from '@app/_services/http-wrapper.service'; import {Registry, TokenRegistry} from '@app/_eth'; +import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' @@ -20,7 +20,7 @@ export class TokenService { tokensSubject = this.tokensList.asObservable(); constructor( - private httpWrapperService: HttpWrapperService, + private httpClient: HttpClient, ) { } async getTokens(): Promise { @@ -30,7 +30,7 @@ export class TokenService { } getTokenBySymbol(symbol: string): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/tokens/${symbol}`); + return this.httpClient.get(`${environment.cicCacheUrl}/tokens/${symbol}`); } async getTokenBalance(address: string): Promise { diff --git a/src/app/_services/transaction.service.ts b/src/app/_services/transaction.service.ts index 365c296..c1f9ba9 100644 --- a/src/app/_services/transaction.service.ts +++ b/src/app/_services/transaction.service.ts @@ -13,8 +13,8 @@ import * as secp256k1 from 'secp256k1'; import {AuthService} from '@app/_services/auth.service'; import {defaultAccount} from '@app/_models'; import {LoggingService} from '@app/_services/logging.service'; -import {HttpWrapperService} from '@app/_services/http-wrapper.service'; import {Registry} from '@app/_eth'; +import {HttpClient} from '@angular/common/http'; const Web3 = require('web3'); const vCard = require('vcard-parser'); @@ -30,18 +30,18 @@ export class TransactionService { registry = new Registry(environment.registryAddress); constructor( - private httpWrapperService: HttpWrapperService, + private httpClient: HttpClient, private authService: AuthService, private userService: UserService, private loggingService: LoggingService ) { } getAllTransactions(offset: number, limit: number): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/tx/${offset}/${limit}`); + return this.httpClient.get(`${environment.cicCacheUrl}/tx/${offset}/${limit}`); } getAddressTransactions(address: string, offset: number, limit: number): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/tx/${address}/${offset}/${limit}`); + return this.httpClient.get(`${environment.cicCacheUrl}/tx/${address}/${offset}/${limit}`); } async setTransaction(transaction, cacheSize: number): Promise { diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index a7c6430..b803775 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -6,7 +6,6 @@ import {first} from 'rxjs/operators'; import {ArgPair, Envelope, Syncable, User} from 'cic-client-meta'; import {MetaResponse} from '@app/_models'; import {LoggingService} from '@app/_services/logging.service'; -import {HttpWrapperService} from '@app/_services/http-wrapper.service'; import {TokenService} from '@app/_services/token.service'; import {AccountIndex, Registry} from '@app/_eth'; import {MutableKeyStore, MutablePgpKeyStore, PGPSigner, Signer} from '@app/_pgp'; @@ -35,8 +34,7 @@ export class UserService { staffSubject = this.staffList.asObservable(); constructor( - private http: HttpClient, - private httpWrapperService: HttpWrapperService, + private httpClient: HttpClient, private loggingService: LoggingService, private tokenService: TokenService ) { @@ -44,16 +42,16 @@ export class UserService { resetPin(phone: string): Observable { const params = new HttpParams().set('phoneNumber', phone); - return this.httpWrapperService.get(`${environment.cicUssdUrl}/pin`, {params}); + return this.httpClient.get(`${environment.cicUssdUrl}/pin`, {params}); } getAccountStatus(phone: string): any { const params = new HttpParams().set('phoneNumber', phone); - return this.httpWrapperService.get(`${environment.cicUssdUrl}/pin`, {params}); + return this.httpClient.get(`${environment.cicUssdUrl}/pin`, {params}); } getLockedAccounts(offset: number, limit: number): any { - return this.httpWrapperService.get(`${environment.cicUssdUrl}/accounts/locked/${offset}/${limit}`); + return this.httpClient.get(`${environment.cicUssdUrl}/accounts/locked/${offset}/${limit}`); } async changeAccountInfo(address: string, name: string, phoneNumber: string, age: string, type: string, bio: string, gender: string, @@ -75,8 +73,8 @@ export class UserService { accountInfo.vcard = vCard.generate(accountInfo.vcard); reqBody.m.data = accountInfo; const accountKey = await User.toKey(address); - this.httpWrapperService.get(`${environment.cicMetaUrl}/${accountKey}`, { headers: this.headers }).pipe(first()).subscribe(async res => { - const syncableAccount: Syncable = Envelope.fromJSON(JSON.stringify(res.body)).unwrap(); + this.httpClient.get(`${environment.cicMetaUrl}/${accountKey}`, { headers: this.headers }).pipe(first()).subscribe(async res => { + const syncableAccount: Syncable = Envelope.fromJSON(JSON.stringify(res)).unwrap(); let update = []; for (const prop in reqBody) { update.push(new ArgPair(prop, reqBody[prop])); @@ -94,67 +92,47 @@ export class UserService { async updateMeta(syncableAccount: Syncable, accountKey: string, headers: HttpHeaders): Promise { const envelope = await this.wrap(syncableAccount , this.signer); const reqBody = envelope.toJSON(); - this.httpWrapperService.put(`${environment.cicMetaUrl}/${accountKey}`, reqBody , { headers }).pipe(first()).subscribe(res => { - this.loggingService.sendInfoLevelMessage(`Response: ${res.body}`); + this.httpClient.put(`${environment.cicMetaUrl}/${accountKey}`, reqBody , { headers }).pipe(first()).subscribe(res => { + this.loggingService.sendInfoLevelMessage(`Response: ${res}`); }); } getAccounts(): void { - this.httpWrapperService.get(`${environment.cicCacheUrl}/accounts`).pipe(first()).subscribe(res => this.accountsList.next(res.body)); + this.httpClient.get(`${environment.cicCacheUrl}/accounts`).pipe(first()).subscribe(res => this.accountsList.next(res)); } getAccountById(id: number): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/accounts/${id}`); + return this.httpClient.get(`${environment.cicCacheUrl}/accounts/${id}`); } getActions(): void { - this.httpWrapperService.get(`${environment.cicCacheUrl}/actions`).pipe(first()).subscribe(res => this.actionsList.next(res.body)); + this.httpClient.get(`${environment.cicCacheUrl}/actions`).pipe(first()).subscribe(res => this.actionsList.next(res)); } getActionById(id: string): any { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/actions/${id}`); + return this.httpClient.get(`${environment.cicCacheUrl}/actions/${id}`); } approveAction(id: string): Observable { - return this.httpWrapperService.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: true }); + return this.httpClient.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: true }); } revokeAction(id: string): Observable { - return this.httpWrapperService.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: false }); + return this.httpClient.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: false }); } getHistoryByUser(id: string): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/history/${id}`); - } - - getStaff(): void { - this.httpWrapperService.get(`${environment.cicCacheUrl}/staff`).pipe(first()).subscribe(res => this.staffList.next(res.body)); - } - - getStaffById(id: string): Observable { - return this.httpWrapperService.get(`${environment.cicCacheUrl}/staff/${id}`); - } - - activateStaff(id: string): Observable { - return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {status: 'activated'}); - } - - deactivateStaff(id: string): Observable { - return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {status: 'deactivated'}); - } - - changeStaffType(id: string, type: string): Observable { - return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {accountType: type}); + return this.httpClient.get(`${environment.cicCacheUrl}/history/${id}`); } getAccountDetailsFromMeta(userKey: string): Observable { - return this.http.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }); + return this.httpClient.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }); } getUser(userKey: string): any { - return this.httpWrapperService.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }) + return this.httpClient.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }) .pipe(first()).subscribe(async res => { - return Envelope.fromJSON(JSON.stringify(res.body)).unwrap(); + return Envelope.fromJSON(JSON.stringify(res)).unwrap(); }); } diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 485edd1..aaaa976 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -21,7 +21,7 @@ export class AppComponent { ) { (async () => { await this.authService.mutableKeyStore.loadKeyring(); - this.authService.getPublicKeys().subscribe(this.authService.mutableKeyStore.importPublicKey) + this.authService.getPublicKeys().subscribe(this.authService.mutableKeyStore.importPublicKey); // this.loggingService.sendInfoLevelMessage(await this.tokenService.getTokens()); })(); this.mediaQuery.addListener(this.onResize); diff --git a/src/app/pages/accounts/account-details/account-details.component.ts b/src/app/pages/accounts/account-details/account-details.component.ts index 2d4d8df..2caed65 100644 --- a/src/app/pages/accounts/account-details/account-details.component.ts +++ b/src/app/pages/accounts/account-details/account-details.component.ts @@ -100,7 +100,7 @@ export class AccountDetailsComponent implements OnInit { }); }); this.userService.getHistoryByUser(this.accountAddress).pipe(first()).subscribe(response => { - this.historyDataSource = new MatTableDataSource(response.body); + this.historyDataSource = new MatTableDataSource(response); this.historyDataSource.paginator = this.historyTablePaginator; this.historyDataSource.sort = this.historyTableSort; }); @@ -203,7 +203,7 @@ export class AccountDetailsComponent implements OnInit { resetPin(): void { this.userService.resetPin(this.account.phone).pipe(first()).subscribe(res => { - this.loggingService.sendInfoLevelMessage(`Response: ${res.body}`); + this.loggingService.sendInfoLevelMessage(`Response: ${res}`); }); } diff --git a/src/app/pages/accounts/accounts.component.ts b/src/app/pages/accounts/accounts.component.ts index 5069b86..b3f6307 100644 --- a/src/app/pages/accounts/accounts.component.ts +++ b/src/app/pages/accounts/accounts.component.ts @@ -40,6 +40,7 @@ export class AccountsComponent implements OnInit { this.userService.accountsSubject.subscribe(accounts => { this.dataSource = new MatTableDataSource(accounts); this.dataSource.paginator = this.paginator; + this.paginator._changePageSize(this.paginator.pageSize); this.dataSource.sort = this.sort; this.accounts = accounts; }); diff --git a/src/app/pages/admin/admin.component.ts b/src/app/pages/admin/admin.component.ts index 129083a..b7931b6 100644 --- a/src/app/pages/admin/admin.component.ts +++ b/src/app/pages/admin/admin.component.ts @@ -51,12 +51,12 @@ export class AdminComponent implements OnInit { } approveAction(action: any): void { - this.userService.approveAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res.body)); + this.userService.approveAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res)); this.userService.getActions(); } revertAction(action: any): void { - this.userService.revokeAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res.body)); + this.userService.revokeAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res)); this.userService.getActions(); } diff --git a/src/app/pages/tokens/token-details/token-details.component.ts b/src/app/pages/tokens/token-details/token-details.component.ts index 63bc9a1..46277fe 100644 --- a/src/app/pages/tokens/token-details/token-details.component.ts +++ b/src/app/pages/tokens/token-details/token-details.component.ts @@ -18,7 +18,7 @@ export class TokenDetailsComponent implements OnInit { ) { this.route.paramMap.subscribe((params: Params) => { this.tokenService.getTokenBySymbol(params.get('id')).pipe(first()).subscribe(res => { - this.token = res.body; + this.token = res; }); }); }