src/app/services/template.service.ts
Properties |
|
Methods |
constructor(http: HttpClient, router: Router, errorService: ErrorStore, authService: AuthService)
|
|||||||||||||||
Defined in src/app/services/template.service.ts:31
|
|||||||||||||||
Parameters :
|
cacheTemplate | ||||||
cacheTemplate(template: Template)
|
||||||
Defined in src/app/services/template.service.ts:70
|
||||||
Parameters :
Returns :
void
|
createPaymentAndTemplate | ||||||
createPaymentAndTemplate(data: CombinedRequest)
|
||||||
Defined in src/app/services/template.service.ts:50
|
||||||
Parameters :
Returns :
Observable<P2PCombinedResponse>
|
createTemplate | ||||||
createTemplate(payload: Template)
|
||||||
Defined in src/app/services/template.service.ts:103
|
||||||
Parameters :
Returns :
Observable<Template>
|
deleteTemplate | ||||||
deleteTemplate(id: string)
|
||||||
Defined in src/app/services/template.service.ts:114
|
||||||
Parameters :
Returns :
Observable<boolean>
|
getAllTemplates | ||||||
getAllTemplates(useCache: )
|
||||||
Defined in src/app/services/template.service.ts:137
|
||||||
Parameters :
Returns :
Observable<[]>
|
getTemplate | ||||||
getTemplate(id: string)
|
||||||
Defined in src/app/services/template.service.ts:79
|
||||||
Parameters :
Returns :
Observable<Template>
|
Private handleError | |||||||||
handleError(error: HttpErrorResponse, title: string)
|
|||||||||
Defined in src/app/services/template.service.ts:161
|
|||||||||
Parameters :
Returns :
any
|
reloadCache |
reloadCache()
|
Defined in src/app/services/template.service.ts:130
|
Returns :
void
|
Private sortTemplates | ||||||
sortTemplates(current: , next: )
|
||||||
Defined in src/app/services/template.service.ts:40
|
||||||
Parameters :
Returns :
1 | -1 | 0
|
updateTemplate | ||||||
updateTemplate(payload: UpdateTemplateRequest)
|
||||||
Defined in src/app/services/template.service.ts:92
|
||||||
Parameters :
Returns :
Observable<boolean>
|
Private cache |
cache:
|
Type : Template[]
|
Defined in src/app/services/template.service.ts:23
|
Private headers |
headers:
|
Default value : new HttpHeaders({
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Expires: '-1',
})
|
Defined in src/app/services/template.service.ts:24
|
Private publisher |
publisher:
|
Default value : new BehaviorSubject<Template[]>(null)
|
Defined in src/app/services/template.service.ts:30
|
Public templates$ |
templates$:
|
Default value : this.publisher.asObservable()
|
Defined in src/app/services/template.service.ts:31
|
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/observable/of';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError, map, tap } from 'rxjs/operators';
import { COMBINED_API, ERROR_MESSAGE, PAYMENT_API, TEMPLATE_API } from '../app.constants';
import {
CombinedRequest,
GetTemplateResponse,
P2PCombinedResponse,
Template,
TemplateUpdate,
UpdateTemplateRequest,
} from '../models';
import { ErrorStore } from '../stores/error.store';
import { AuthService } from './auth.service';
@Injectable()
export class TemplateService {
private cache: Template[];
private headers = new HttpHeaders({
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Expires: '-1',
});
private publisher = new BehaviorSubject<Template[]>(null);
public templates$ = this.publisher.asObservable();
constructor(
private http: HttpClient,
private router: Router,
private errorService: ErrorStore,
private authService: AuthService
) {}
private sortTemplates(current, next) {
const a = current.name.toLowerCase();
const b = next.name.toLowerCase();
// tslint:disable-next-line:curly
if (a < b) return -1;
// tslint:disable-next-line:curly
if (a > b) return 1;
return 0;
}
createPaymentAndTemplate(data: CombinedRequest): Observable<P2PCombinedResponse> {
return this.http.post<P2PCombinedResponse>(`${PAYMENT_API}/create`, data).pipe(
tap((res) => {
const template = res.template;
const isNotInCache = this.cache.filter((t) => t.id === template.id).length === 0;
if (isNotInCache) {
template.firstCharOfName = template.name.charAt(0).toUpperCase();
this.cache.push(template);
this.cache = this.cache.sort(this.sortTemplates);
}
}),
catchError((error) => {
const title = error.error || 'Failed To Create Payee & Payment';
this.errorService.addError(title, '');
this.errorService.displayErrors();
return Observable.of(null);
})
);
}
cacheTemplate(template: Template): void {
const isNotInCache = this.cache.filter((t) => t.id === template.id).length === 0;
if (isNotInCache) {
template.firstCharOfName = template.name.charAt(0).toUpperCase();
this.cache.push(template);
this.cache = this.cache.sort(this.sortTemplates);
}
}
getTemplate(id: string): Observable<Template> {
const url = `${TEMPLATE_API}/${id}`;
if (this.cache != null && this.cache !== undefined) {
const found = this.cache.filter((t) => t.id === id);
const template = found.length > 0 ? found[0] : null;
return Observable.of(template);
}
return this.http.get<GetTemplateResponse>(url, { headers: this.headers }).pipe(
map((res) => res.template),
catchError((error) => this.handleError(error, 'Failed To Retrieve Template'))
);
}
updateTemplate(payload: UpdateTemplateRequest): Observable<boolean> {
const url = `${TEMPLATE_API}`;
return this.http.patch(url, payload).pipe(
map((res) => {
console.log('template patched');
return true;
}),
catchError((error) => this.handleError(error, 'Failed To Update Template'))
);
}
createTemplate(payload: Template): Observable<Template> {
const url = `${TEMPLATE_API}/create`;
return this.http.post<Template>(url, payload).pipe(
tap((template) => this.cache.push(template)),
catchError((error) => {
const title = 'Failed To Create Template';
return this.handleError(error, title);
})
);
}
deleteTemplate(id: string): Observable<boolean> {
const url = `${TEMPLATE_API}/${id}`;
return this.http.delete(url).pipe(
map((res) => {
return true;
}),
tap((res) => {
this.cache = this.cache.filter((t) => t.id !== id);
}),
catchError((error) => {
const title = 'Failed To Delete Template';
return this.handleError(error, title);
})
);
}
reloadCache() {
console.log('reloading template cache');
this.getAllTemplates(false).subscribe(() => {
console.log('template cache reloaded');
});
}
getAllTemplates(useCache = true): Observable<Template[]> {
const url = `${TEMPLATE_API}`;
if (useCache && this.cache != null && this.cache !== undefined) {
this.publisher.next(this.cache);
return Observable.of(this.cache);
}
return this.http.get<Template[]>(url, { headers: this.headers }).pipe(
map((templates) => {
if (!templates) {
const title = 'Failed To Retrieve Templates';
this.errorService.addError(title, ERROR_MESSAGE);
this.errorService.displayErrors();
return null;
}
this.cache = templates.map((t) => {
t.firstCharOfName = t.name.charAt(0).toUpperCase();
return t;
});
this.publisher.next(this.cache);
return this.cache;
})
);
}
private handleError(error: HttpErrorResponse, title: string) {
this.errorService.addError(title, ERROR_MESSAGE);
this.errorService.displayErrors();
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an ErrorObservable with a user-facing error message
return new ErrorObservable('Something bad happened; please try again later.');
}
}