forked from hotosm/tasking-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseProjectsQueryAPI.js
More file actions
241 lines (223 loc) · 7.28 KB
/
UseProjectsQueryAPI.js
File metadata and controls
241 lines (223 loc) · 7.28 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { useEffect, useReducer } from 'react';
import { useSelector } from 'react-redux';
import {
useQueryParams,
encodeQueryParams,
StringParam,
NumberParam,
BooleanParam,
} from 'use-query-params';
import queryString from 'query-string';
import axios from 'axios';
import { subMonths, format } from 'date-fns';
import { CommaArrayParam } from '../utils/CommaArrayParam';
import { useThrottle } from '../hooks/UseThrottle';
import { remapParamsToAPI } from '../utils/remapParamsToAPI';
import { API_URL } from '../config';
const projectQueryAllSpecification = {
sandbox:StringParam,
difficulty: StringParam,
organisation: StringParam,
campaign: StringParam,
team: NumberParam,
location: StringParam,
types: CommaArrayParam,
exactTypes: BooleanParam,
interests: NumberParam,
page: NumberParam,
text: StringParam,
orderBy: StringParam,
orderByType: StringParam,
createdByMe: BooleanParam,
managedByMe: BooleanParam,
favoritedByMe: BooleanParam,
mappedByMe: BooleanParam,
status: StringParam,
action: StringParam,
stale: BooleanParam,
createdFrom: StringParam,
basedOnMyInterests: BooleanParam,
omitMapResults: BooleanParam,
partnerId: NumberParam,
partnershipFrom: StringParam,
partnershipTo: StringParam,
downloadAsCSV: BooleanParam,
view: StringParam,
imagery: StringParam,
};
/* This can be passed into project API or used independently */
export const useExploreProjectsQueryParams = () => {
return useQueryParams(projectQueryAllSpecification);
};
/* The API uses slightly different JSON keys than the queryParams,
this fn takes an object with queryparam keys and outputs JSON keys
while maintaining the same values */
const backendToQueryConversion = {
sandbox:'sandbox',
difficulty: 'difficulty',
campaign: 'campaign',
team: 'teamId',
organisation: 'organisationName',
location: 'country',
types: 'mappingTypes',
exactTypes: 'mappingTypesExact',
interests: 'interests',
text: 'textSearch',
page: 'page',
orderBy: 'orderBy',
orderByType: 'orderByType',
createdByMe: 'createdByMe',
managedByMe: 'managedByMe',
favoritedByMe: 'favoritedByMe',
mappedByMe: 'mappedByMe',
status: 'projectStatuses',
action: 'action',
stale: 'lastUpdatedTo',
createdFrom: 'createdFrom',
basedOnMyInterests: 'basedOnMyInterests',
omitMapResults: 'omitMapResults',
imagery: 'imagery',
};
const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return {
...state,
isLoading: true,
isError: false,
};
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
projects: action.payload.results,
mapResults: action.payload.mapResults,
pagination: action.payload.pagination,
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true,
};
default:
console.log(action);
throw new Error();
}
};
const defaultInitialData = {
mapResults: {
features: [],
type: 'FeatureCollection',
},
results: [],
pagination: { hasNext: false, hasPrev: false, page: 1 },
};
export const useProjectsQueryAPI = (
initialData = defaultInitialData,
ExternalQueryParamsState,
forceUpdate = null,
) => {
const throttledExternalQueryParamsState = useThrottle(ExternalQueryParamsState, 1500);
/* Get the user bearer token from the Redux store */
const token = useSelector((state) => state.auth.token);
const locale = useSelector((state) => state.preferences['locale']);
const action = useSelector((state) => state.preferences['action']);
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: true,
isError: false,
projects: initialData.results,
mapResults: initialData.mapResults,
pagination: initialData.pagination,
queryParamsState: ExternalQueryParamsState[0],
});
useEffect(() => {
let didCancel = false;
let cancel;
const fetchData = async () => {
const CancelToken = axios.CancelToken;
dispatch({
type: 'FETCH_INIT',
});
let headers = {
'Content-Type': 'application/json',
'Accept-Language': locale ? locale.replace('-', '_') : 'en',
};
if (token) {
headers['Authorization'] = `Token ${token}`;
}
const paramsRemapped = remapParamsToAPI(
throttledExternalQueryParamsState,
backendToQueryConversion,
);
// it's needed in order to query by action when the user goes to /explore page
if (paramsRemapped.action === undefined && action) {
paramsRemapped.action = action;
}
if (paramsRemapped.lastUpdatedTo) {
paramsRemapped.lastUpdatedTo = format(subMonths(Date.now(), 6), 'yyyy-MM-dd');
}
try {
const result = await axios({
url: `${API_URL}projects/`,
method: 'get',
headers: headers,
params: paramsRemapped,
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = { end: c, params: throttledExternalQueryParamsState };
}),
});
if (!didCancel) {
if (result && result.headers && result.headers['content-type'].indexOf('json') !== -1) {
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
} else {
dispatch({ type: 'FETCH_FAILURE' });
}
} else {
cancel && cancel.end();
}
} catch (error) {
/* if cancelled, this setting state of unmounted
* component with dispatch would be a memory leak */
if (
!didCancel &&
error &&
error.response &&
error.response.data &&
error.response.data.Error === 'No projects found'
) {
const zeroPayload = Object.assign(defaultInitialData, { pagination: { total: 0 } });
/* TODO(tdk): when 404 and page > 1, re-request page 1 */
dispatch({ type: 'FETCH_SUCCESS', payload: zeroPayload });
} else if (!didCancel && error.response) {
const errorResPayload = Object.assign(defaultInitialData, { error: error.response });
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
dispatch({ type: 'FETCH_FAILURE', payload: errorResPayload });
} else if (!didCancel && error.request) {
const errorReqPayload = Object.assign(defaultInitialData, { error: error.request });
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
dispatch({ type: 'FETCH_FAILURE', payload: errorReqPayload });
} else if (!didCancel) {
dispatch({ type: 'FETCH_FAILURE' });
} else {
cancel && cancel.end();
}
}
};
fetchData();
return () => {
didCancel = true;
cancel && cancel.end();
};
}, [throttledExternalQueryParamsState, forceUpdate, token, locale, action]);
return [state, dispatch];
};
export const stringify = (obj) => {
const encodedQuery = encodeQueryParams(projectQueryAllSpecification, obj);
return queryString.stringify(encodedQuery);
};