-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathlive-data.ts
56 lines (51 loc) · 1.48 KB
/
live-data.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
import { HTTPClient2 } from '../out/petstore.yaml/client/client';
import { Monad } from 'fp-ts-rxjs/Observable';
import { Observable, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { catchError, map, startWith, switchMap, take } from 'rxjs/operators';
import { failure, pending, RemoteData, success } from '@devexperts/remote-data-ts';
import { getRemoteDataM } from '@devexperts/remote-data-ts/dist/remote-data-t';
import { MonadThrow2 } from 'fp-ts/MonadThrow';
export const URI = 'LiveData' as const;
export type URI = typeof URI;
export type LiveData<E, A> = Observable<RemoteData<E, A>>;
declare module 'fp-ts/HKT' {
interface URItoKind2<E, A> {
readonly [URI]: LiveData<E, A>;
}
}
const remoteDataMonad: MonadThrow2<URI> = {
...getRemoteDataM(Monad),
URI,
throwError: e => of(failure(e)),
};
export const liveDataClient: HTTPClient2<URI> = {
...remoteDataMonad,
request: ({ body, headers, method, query, url }) =>
ajax({
body: body && JSON.stringify(body),
url: query ? `${url}?${query}` : url,
headers,
method,
}).pipe(
map(response => success(response.response)),
catchError(remoteDataMonad.throwError),
startWith(pending),
),
};
export const liveDataClientWithAuth = (token$: Observable<string>): HTTPClient2<URI> => ({
...liveDataClient,
request: req =>
token$.pipe(
take(1),
switchMap(token =>
liveDataClient.request({
...req,
headers: {
...req.headers,
Authorization: `Bearer ${token}`,
},
}),
),
),
});