-
Notifications
You must be signed in to change notification settings - Fork 8
/
rx-http-request.js
38 lines (30 loc) · 1.42 KB
/
rx-http-request.js
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
import { RxHR } from '@akanass/rx-http-request';
import { map, flatMap } from 'rxjs/operators';
import { combineLatest } from 'rxjs';
const BASE_PATH = `https://maciejtreder.github.io/asynchronous-javascript`;
const directors$ = RxHR.get(`${BASE_PATH}/directors/`, {json: true}).pipe(map(response => response.body));
const directorId$ = directors$.pipe(
map(directors => directors.find(director => director.name === "Quentin Tarantino").id)
);
const directorMovies$ = directorId$.pipe(
flatMap(id => {
return RxHR.get(`${BASE_PATH}/directors/${id}/movies`, {json: true})
}),
map(resp => resp.body)
);
function getAverageScore(movie) {
const reducer = (accumulator, currentValue) => accumulator + currentValue.rating;
return RxHR.get(`${BASE_PATH}/movies/${movie.id}/reviews`, {json: true}).pipe(
map(response => response.body.reduce(reducer, 0) / response.body.length),
map(response => { return {title: movie.title, averageScore: response}; })
);
}
const moviesRatings$ = directorMovies$.pipe(
flatMap(movies => {
const observables$ = [];
movies.forEach(movie => observables$.push(getAverageScore(movie)));
return combineLatest(observables$);
})
);
const best$ = moviesRatings$.pipe(map(movies => movies.sort((m1, m2) => m2.averageScore - m1.averageScore)[0].title));
best$.subscribe(result => console.log(`The best movie by Quentin Tarantino is... ${result}!`));