|
| 1 | +import * as types from '../constants/ActionTypes'; |
| 2 | + |
| 3 | +function selectReddit(reddit) { |
| 4 | + return { |
| 5 | + type: types.SELECT_REDDIT, |
| 6 | + reddit |
| 7 | + }; |
| 8 | +} |
| 9 | + |
| 10 | +function invalidateReddit(reddit) { |
| 11 | + return { |
| 12 | + type: types.INVALIDATE_REDDIT, |
| 13 | + reddit |
| 14 | + }; |
| 15 | +} |
| 16 | + |
| 17 | +function requestPosts(reddit) { |
| 18 | + return { |
| 19 | + type: types.REQUEST_POSTS, |
| 20 | + reddit |
| 21 | + }; |
| 22 | +} |
| 23 | + |
| 24 | +function receivePosts(reddit, json) { |
| 25 | + return { |
| 26 | + type: types.RECEIVE_POSTS, |
| 27 | + reddit: reddit, |
| 28 | + posts: json.data.children.map(child => child.data), |
| 29 | + receivedAt: Date.now() |
| 30 | + }; |
| 31 | +} |
| 32 | + |
| 33 | +export default function asyncService($http) { |
| 34 | + function fetchPosts(reddit) { |
| 35 | + return dispatch => { |
| 36 | + dispatch(requestPosts(reddit)); |
| 37 | + return $http.get(`http://www.reddit.com/r/${reddit}.json`) |
| 38 | + .then(response => response.data) |
| 39 | + .then(json => dispatch(receivePosts(reddit, json))); |
| 40 | + }; |
| 41 | + } |
| 42 | + |
| 43 | + function shouldFetchPosts(state, reddit) { |
| 44 | + const posts = state.postsByReddit[reddit]; |
| 45 | + if (!posts) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + if (posts.isFetching) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + return posts.didInvalidate; |
| 52 | + } |
| 53 | + |
| 54 | + function fetchPostsIfNeeded(reddit) { |
| 55 | + return (dispatch, getState) => { |
| 56 | + if (shouldFetchPosts(getState(), reddit)) { |
| 57 | + return dispatch(fetchPosts(reddit)); |
| 58 | + } |
| 59 | + }; |
| 60 | + } |
| 61 | + |
| 62 | + return { |
| 63 | + selectReddit, |
| 64 | + invalidateReddit, |
| 65 | + fetchPostsIfNeeded |
| 66 | + }; |
| 67 | +} |
0 commit comments