-
Notifications
You must be signed in to change notification settings - Fork 1k
/
api.js
52 lines (42 loc) · 1.34 KB
/
api.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const api = `https://hacker-news.firebaseio.com/v0`
const json = '.json?print=pretty'
function removeDead (posts) {
return posts.filter(Boolean).filter(({ dead }) => dead !== true)
}
function removeDeleted (posts) {
return posts.filter(({ deleted }) => deleted !== true)
}
function onlyComments (posts) {
return posts.filter(({ type }) => type === 'comment')
}
function onlyPosts (posts) {
return posts.filter(({ type }) => type === 'story')
}
export function fetchItem (id) {
return fetch(`${api}/item/${id}${json}`)
.then((res) => res.json())
}
export function fetchComments (ids) {
return Promise.all(ids.map(fetchItem))
.then((comments) => removeDeleted(onlyComments(removeDead(comments))))
}
export function fetchMainPosts (type) {
return fetch(`${api}/${type}stories${json}`)
.then((res) => res.json())
.then((ids) => {
if (!ids) {
throw new Error(`There was an error fetching the ${type} posts.`)
}
return ids.slice(0, 50)
})
.then((ids) => Promise.all(ids.map(fetchItem)))
.then((posts) => removeDeleted(onlyPosts(removeDead(posts))))
}
export function fetchUser (id) {
return fetch(`${api}/user/${id}${json}`)
.then((res) => res.json())
}
export function fetchPosts (ids) {
return Promise.all(ids.map(fetchItem))
.then((posts) => removeDeleted(onlyPosts(removeDead(posts))))
}