File

src/app/services/template.service.ts

Index

Properties
Methods

Constructor

constructor(http: HttpClient, router: Router, errorService: ErrorStore, authService: AuthService)
Parameters :
Name Type Optional
http HttpClient no
router Router no
errorService ErrorStore no
authService AuthService no

Methods

cacheTemplate
cacheTemplate(template: Template)
Parameters :
Name Type Optional
template Template no
Returns : void
createPaymentAndTemplate
createPaymentAndTemplate(data: CombinedRequest)
Parameters :
Name Type Optional
data CombinedRequest no
createTemplate
createTemplate(payload: Template)
Parameters :
Name Type Optional
payload Template no
deleteTemplate
deleteTemplate(id: string)
Parameters :
Name Type Optional
id string no
Returns : Observable<boolean>
getAllTemplates
getAllTemplates(useCache: )
Parameters :
Name Optional Default value
useCache no true
Returns : Observable<[]>
getTemplate
getTemplate(id: string)
Parameters :
Name Type Optional
id string no
Private handleError
handleError(error: HttpErrorResponse, title: string)
Parameters :
Name Type Optional
error HttpErrorResponse no
title string no
Returns : any
reloadCache
reloadCache()
Returns : void
Private sortTemplates
sortTemplates(current: , next: )
Parameters :
Name Optional
current no
next no
Returns : 1 | -1 | 0
updateTemplate
updateTemplate(payload: UpdateTemplateRequest)
Parameters :
Name Type Optional
payload UpdateTemplateRequest no
Returns : Observable<boolean>

Properties

Private cache
cache: Template[]
Type : Template[]
Private headers
headers:
Default value : new HttpHeaders({ 'Cache-Control': 'no-cache', Pragma: 'no-cache', Expires: '-1', })
Private publisher
publisher:
Default value : new BehaviorSubject<Template[]>(null)
Public templates$
templates$:
Default value : this.publisher.asObservable()
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.');
  }
}

results matching ""

    No results matching ""