/
hacker-news.service.ts
58 lines (49 loc) · 1.83 KB
/
hacker-news.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
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { IAvailableTags, IBaseStory, IResultList, IBaseStoryType, IHackerNews, Hit, IStory } from 'interfaces';
import { forkJoin, Observable, of } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HackerNewsService {
BASE_URL = 'https://hacker-news.firebaseio.com/v0';
BASE_URL_ALGOLIA = 'https://hn.algolia.com/api/v1';
constructor(
private http: HttpClient
) {
}
/**
* To get newest stories
*/
getStories(page: number = 1, pageSize: number = 20, type = IBaseStoryType.TOP): Observable<IResultList> {
return this.http.get<any>(`${this.BASE_URL}/${type}.json?print=pretty`).pipe(
mergeMap((ids) => forkJoin([ of(ids.length), ...ids.slice((page - 1) * pageSize, page * pageSize).map(id => this.getStory(id)) ])),
map(data => {
return {
total: data[ 0 ],
data : data.slice(1)
};
})
);
}
/**
* To get story detail (comments)
*/
getStory(itemId: number): Observable<IBaseStory> {
return this.http.get<IBaseStory>(`${this.BASE_URL}/item/${itemId}.json?print=pretty`);
}
/**
* =============== algolia.com ==================
*/
getStoriesByAlgolia(query = '', page = 1, sortType: 'search' | 'search_by_date' = 'search', tags = IAvailableTags.STORY): Observable<IHackerNews> {
const params = new HttpParams().append('tags', tags).append('page', page.toString());
if (query) {
params.append('query', query);
}
return this.http.get<IHackerNews>(`${this.BASE_URL_ALGOLIA}/${sortType}`, { params, responseType: 'json' });
}
getStoryByAlgolia(itemId: number): Observable<IStory> {
return this.http.get<IStory>(`${this.BASE_URL_ALGOLIA}/items/${itemId}`);
}
}