|
1 /* eslint-disable func-names */ |
|
2 import fetch from 'isomorphic-fetch'; |
|
3 import _ from 'lodash'; |
|
4 |
|
5 import { getTerms, toBase64 } from './utils'; |
|
6 |
|
7 |
|
8 export const REQUEST_ANNOTATIONS = 'REQUEST_ANNOTATIONS'; |
|
9 export function requestAnnotations(url) { |
|
10 return { |
|
11 type: REQUEST_ANNOTATIONS, |
|
12 url, |
|
13 }; |
|
14 } |
|
15 |
|
16 export const RECEIVE_ANNOTATIONS = 'RECEIVE_ANNOTATIONS'; |
|
17 export function receiveAnnotations(url, annotations, terms) { |
|
18 return { |
|
19 type: RECEIVE_ANNOTATIONS, |
|
20 url, |
|
21 annotations, |
|
22 terms, |
|
23 receivedAt: Date.now(), |
|
24 }; |
|
25 } |
|
26 |
|
27 export const RECEIVE_MESSAGES_COUNT = 'RECEIVE_MESSAGES_COUNT'; |
|
28 export function receiveMessagesCount(url, terms, terms64, messagesCount) { |
|
29 return { |
|
30 type: RECEIVE_MESSAGES_COUNT, |
|
31 terms, |
|
32 terms64, |
|
33 messagesCount, |
|
34 }; |
|
35 } |
|
36 |
|
37 export const REQUEST_MESSAGES_COUNT = 'REQUEST_MESSAGES_COUNT'; |
|
38 export function requestMessagesCount(url, terms, terms64) { |
|
39 return { |
|
40 type: REQUEST_MESSAGES_COUNT, |
|
41 url, |
|
42 terms, |
|
43 terms64, |
|
44 }; |
|
45 } |
|
46 |
|
47 export const FETCH_MESSAGES_COUNT = 'FETCH_MESSAGES_COUNT'; |
|
48 export function fetchMessagesCount(terms, discussionUrl) { |
|
49 const url = `${discussionUrl}count`; |
|
50 const terms64 = _.map(terms, toBase64); |
|
51 |
|
52 return function (dispatch) { |
|
53 dispatch(requestMessagesCount(url, terms, terms64)); |
|
54 |
|
55 if (!discussionUrl) { |
|
56 return dispatch(receiveMessagesCount(url, terms, terms64, {})); |
|
57 } |
|
58 |
|
59 return fetch(url, { |
|
60 method: 'POST', |
|
61 headers: { |
|
62 'Content-Type': 'application/json', |
|
63 }, |
|
64 body: JSON.stringify(terms64), |
|
65 }) |
|
66 .then( |
|
67 response => response.json(), |
|
68 error => console.log('An error occured.', error), // eslint-disable-line no-console |
|
69 ) |
|
70 .then( |
|
71 json => dispatch(receiveMessagesCount(url, terms, terms64, json)), |
|
72 ); |
|
73 }; |
|
74 } |
|
75 |
|
76 export const FETCH_ANNOTATIONS = 'FETCH_ANNOTATIONS'; |
|
77 export function fetchAnnotations(url, discussionUrl) { |
|
78 return function (dispatch) { |
|
79 dispatch(requestAnnotations(url)); |
|
80 |
|
81 return fetch(url) |
|
82 .then( |
|
83 response => response.json(), |
|
84 error => console.log('An error occured.', error), // eslint-disable-line no-console |
|
85 ) |
|
86 .then((json) => { |
|
87 const annotations = json.rows; |
|
88 const terms = getTerms(annotations); |
|
89 |
|
90 dispatch(fetchMessagesCount(Object.keys(terms), discussionUrl)); |
|
91 dispatch(receiveAnnotations(url, annotations, terms)); |
|
92 }); |
|
93 }; |
|
94 } |