1import { HttpClient, HttpHeaders } from '@angular/common/http';
2import { Inject, Injectable, InjectionToken } from '@angular/core';
3import { Observable, of } from 'rxjs';
4import { catchError, map, tap } from 'rxjs/operators';
5
6import { Golden } from './golden';
7
8export const ACCESS_TOKEN = new InjectionToken<string>('token');
9export const SERVICE_PORT = new InjectionToken<string>('port');
10
11@Injectable({ providedIn: 'root' })
12export class GoldensService {
13  private serverRoot: string;
14  private defaultHeaders: { [heder: string]: string };
15
16  constructor(
17    private http: HttpClient,
18    @Inject(ACCESS_TOKEN) config: string,
19    @Inject(SERVICE_PORT) port: string,
20  ) {
21    this.serverRoot = `http://localhost:${port}`;
22    this.defaultHeaders = {
23      'Golden-Access-Token': config,
24    };
25  }
26
27  getGoldens(): Observable<Golden[]> {
28    return this.http
29      .get<
30        Golden[]
31      >(`${this.serverRoot}/service/list`, { headers: this.defaultHeaders })
32      .pipe(
33        tap((x) => console.log(`listed goldens, got ${x.length} results`)),
34        catchError(this.handleError<Golden[]>('e')),
35      );
36  }
37
38  refreshGoldens(clear: boolean): Observable<Golden[]> {
39    return this.http
40      .post<Golden[]>(
41        `${this.serverRoot}/service/refresh`,
42        { clear },
43        {
44          headers: {
45            ...this.defaultHeaders,
46            'Content-Type': 'application/json',
47          },
48        },
49      )
50      .pipe(
51        tap((_) => console.log(`refreshed goldens (clear)`)),
52        catchError(this.handleError<Golden[]>('e')),
53      );
54  }
55
56  updateGolden(golden: Golden): Observable<void> {
57    return this.http
58      .put<void>(
59        `${this.serverRoot}/service/update?id=${golden.id}`,
60        {},
61        { headers: this.defaultHeaders },
62      )
63      .pipe(
64        tap((_) => {
65          console.log(`updated golden`);
66          golden.updated = true;
67        }),
68        catchError(this.handleError<void>('update')),
69      );
70  }
71
72  private handleError<T>(operation = 'operation', result?: T) {
73    return (error: any): Observable<T> => {
74      console.error(error);
75
76      // Let the app keep running by returning an empty result.
77      return of(result as T);
78    };
79  }
80}
81