-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.ts
executable file
·65 lines (57 loc) · 1.59 KB
/
service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Observable } from 'rxjs';
import { of } from 'rxjs';
import { catchError, switchMap, tap } from 'rxjs/operators';
import { fromFetch } from 'rxjs/fetch';
export type HttpError = {
code?: string;
message: string;
stack?: string;
};
export class APIService<Model> {
private fetch: (
input: string | Request,
init?: RequestInit,
) => Observable<Response>;
/**
* Constructor
* To facilitate testing allow dependency injection of fetchFrom
* @param fetch
*/
constructor(
fetchDependency: (
input: string | Request,
init?: RequestInit,
) => Observable<Response> = fromFetch,
) {
this.fetch = fetchDependency;
}
all(url: string): Observable<Model[] | HttpError> {
return this.fetch(url).pipe(
/**
* fetch does not trigger catchError for http error status codes returned by the server
* fetch triggers a catchError when errors occur client side
*/
tap(response => {
console.log(`Fetch response is ${response}`);
}),
switchMap(response => {
if (response.ok) {
return response.json() as Promise<Model[]>;
} else {
return of({
message: `Error ${response.statusText}`,
code: `Error ${response.status}`,
});
}
}),
tap(data =>
console.log(`APIService data => ${JSON.stringify(data, null, 2)}`),
),
catchError(err => {
// Errors such as network connection errors, timeout etc caught here
console.error(err);
return of({ message: err.message });
}),
);
}
}