-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathasyncService.js
67 lines (59 loc) · 1.33 KB
/
asyncService.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import * as types from '../constants/ActionTypes';
function selectReddit(reddit) {
return {
type: types.SELECT_REDDIT,
reddit
};
}
function invalidateReddit(reddit) {
return {
type: types.INVALIDATE_REDDIT,
reddit
};
}
function requestPosts(reddit) {
return {
type: types.REQUEST_POSTS,
reddit
};
}
function receivePosts(reddit, json) {
return {
type: types.RECEIVE_POSTS,
reddit: reddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
export default function asyncService($http) {
function fetchPosts(reddit) {
return dispatch => {
dispatch(requestPosts(reddit));
return $http.get(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.data)
.then(json => dispatch(receivePosts(reddit, json)));
};
}
function shouldFetchPosts(state, reddit) {
const posts = state.postsByReddit.get(reddit);
if (!posts) {
return true;
}
if (posts.get('isFetching')) {
return false;
}
return posts.get('didInvalidate');
}
function fetchPostsIfNeeded(reddit) {
return (dispatch, getState) => {
if (shouldFetchPosts(getState(), reddit)) {
return dispatch(fetchPosts(reddit));
}
};
}
return {
selectReddit,
invalidateReddit,
fetchPostsIfNeeded
};
}