-
Notifications
You must be signed in to change notification settings - Fork 118
/
withList.js
347 lines (280 loc) · 12.1 KB
/
withList.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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
### withList
Paginated items container
Options:
- queryName: an arbitrary name for the query
- collection: the collection to fetch the documents from
- fragment: the fragment that defines which properties to fetch
- fragmentName: the name of the fragment, passed to getFragment
- limit: the number of documents to show initially
- pollInterval: how often the data should be updated, in ms (set to 0 to disable polling)
- terms: an object that defines which documents to fetch
Props Received:
- terms: an object that defines which documents to fetch
Terms object can have the following properties:
- view: String
- userId: String
- cat: String
- date: String
- after: String
- before: String
- enableCache: Boolean
- listId: String
- query: String # search query
- postId: String
- limit: String
*/
import React, { Component } from 'react';
import { withApollo, graphql } from 'react-apollo';
import gql from 'graphql-tag';
import update from 'immutability-helper';
import { getSetting, getFragment, getFragmentName, getCollection } from 'meteor/vulcan:core';
import Mingo from 'mingo';
import compose from 'recompose/compose';
import withState from 'recompose/withState';
import withIdle from './withIdle.jsx';
import withIdlePollingStopper from './withIdlePollingStopper.jsx'
// import IDLE_STATUSES from 'meteor/vulcan:core'
const withList = (options) => {
// console.log(options)
const {
collectionName,
stopPollingIdleStatus = "INACTIVE",
limit = 10,
pollInterval = getSetting('pollInterval', 20000),
totalResolver = true,
enableCache = false,
extraQueries,
} = options;
const collection = options.collection || getCollection(collectionName);
const queryName = options.queryName || `${collection.options.collectionName}ListQuery`;
const listResolverName = collection.options.resolvers.list && collection.options.resolvers.list.name;
const totalResolverName = collection.options.resolvers.total && collection.options.resolvers.total.name;
let fragment;
if (options.fragment) {
fragment = options.fragment;
} else if (options.fragmentName) {
fragment = getFragment(options.fragmentName);
} else {
fragment = getFragment(`${collection.options.collectionName}DefaultFragment`);
}
const fragmentName = getFragmentName(fragment);
// build graphql query from options
const query = gql`
query ${queryName}($terms: JSON) {
${totalResolver ? `${totalResolverName}(terms: $terms)` : ``}
${listResolverName}(terms: $terms) {
__typename
...${fragmentName}
}
${extraQueries || ''}
}
${fragment}
`;
return compose(
// wrap component with Apollo HoC to give it access to the store
withApollo,
// wrap component with HoC that manages the terms object via its state
withState('paginationTerms', 'setPaginationTerms', props => {
// get initial limit from props, or else options
const paginationLimit = props.terms && props.terms.limit || limit;
const paginationTerms = {
limit: paginationLimit,
itemsPerPage: paginationLimit,
};
return paginationTerms;
}),
// wrap component with withIdle to get access to idle state
withIdle,
// wrap component with graphql HoC
graphql(
query,
{
alias: 'withList',
// graphql query options
options({terms, paginationTerms, client: apolloClient}) {
// get terms from options, then props, then pagination
const mergedTerms = {...options.terms, ...terms, ...paginationTerms};
const graphQLOptions = {
variables: {
terms: mergedTerms,
},
// note: pollInterval can be set to 0 to disable polling (20s by default)
// pollInterval: 0,
reducer: (previousResults, action) => {
// see queryReducer function defined below
return queryReducer(previousResults, action, collection, mergedTerms, listResolverName, totalResolverName, queryName, apolloClient);
},
};
if (options.fetchPolicy) {
graphQLOptions.fetchPolicy = options.fetchPolicy
}
return graphQLOptions;
},
// define props returned by graphql HoC
props(props) {
const refetch = props.data.refetch,
// results = Utils.convertDates(collection, props.data[listResolverName]),
results = props.data[listResolverName],
totalCount = props.data[totalResolverName],
networkStatus = props.data.networkStatus,
stopPolling = props.data.stopPolling,
startPolling = props.data.startPolling,
loading = props.data.loading,
error = props.data.error,
propertyName = options.propertyName || 'results';
if (error) {
// eslint-disable-next-line no-console
console.log(error);
}
return {
// see https://github.com/apollostack/apollo-client/blob/master/src/queries/store.ts#L28-L36
// note: loading will propably change soon https://github.com/apollostack/apollo-client/issues/831
loading: networkStatus === 1,
[ propertyName ]: results,
totalCount,
refetch,
stopPolling,
startPolling,
networkStatus,
error,
count: results && results.length,
// regular load more (reload everything)
loadMore(providedTerms) {
// if new terms are provided by presentational component use them, else default to incrementing current limit once
const newTerms = typeof providedTerms === 'undefined' ? { /*...props.ownProps.terms,*/ ...props.ownProps.paginationTerms, limit: results.length + props.ownProps.paginationTerms.itemsPerPage } : providedTerms;
props.ownProps.setPaginationTerms(newTerms);
},
// incremental loading version (only load new content)
// note: not compatible with polling
loadMoreInc(providedTerms) {
// get terms passed as argument or else just default to incrementing the offset
const newTerms = typeof providedTerms === 'undefined' ? { ...props.ownProps.terms, ...props.ownProps.paginationTerms, offset: results.length } : providedTerms;
return props.data.fetchMore({
variables: { terms: newTerms }, // ??? not sure about 'terms: newTerms'
updateQuery(previousResults, { fetchMoreResult }) {
// no more post to fetch
if (!fetchMoreResult.data) {
return previousResults;
}
const newResults = {};
newResults[listResolverName] = [...previousResults[listResolverName], ...fetchMoreResult.data[listResolverName]];
// return the previous results "augmented" with more
return {...previousResults, ...newResults};
},
});
},
fragmentName,
fragment,
...props.ownProps, // pass on the props down to the wrapped component
data: props.data,
};
},
}
),
withIdlePollingStopper(stopPollingIdleStatus)
);
}
// define query reducer separately
const queryReducer = (previousResults, action, collection, mergedTerms, listResolverName, totalResolverName, queryName, apolloClient) => {
// if collection has no mutations defined, just return previous results
if (!collection.options.mutations) {
return previousResults;
}
const newMutationName = collection.options.mutations.new && collection.options.mutations.new.name;
const editMutationName = collection.options.mutations.edit && collection.options.mutations.edit.name;
const removeMutationName = collection.options.mutations.remove && collection.options.mutations.remove.name;
let newResults = previousResults;
// get mongo selector and options objects based on current terms
const result = collection.getParameters(mergedTerms, apolloClient);
const { selector, options } = result;
const mingoQuery = Mingo.Query(selector);
// function to remove a document from a results object, used by edit and remove cases below
const removeFromResults = (results, document) => {
const listWithoutDocument = results[listResolverName].filter(doc => doc._id !== document._id);
const newResults = update(results, {
[listResolverName]: { $set: listWithoutDocument }, // ex: postsList
[totalResolverName]: { $set: results[totalResolverName] - 1 } // ex: postsListTotal
});
return newResults;
}
// add document to a results object
const addToResults = (results, document) => {
return update(results, {
[listResolverName]: { $unshift: [document] },
[totalResolverName]: { $set: results[totalResolverName] + 1 }
});
}
// reorder results according to a sort
const reorderResults = (results, sort) => {
const list = results[listResolverName];
// const convertedList = Utils.convertDates(collection, list); // convert date strings to date objects
const convertedList = list;
const cursor = mingoQuery.find(convertedList);
const sortedList = cursor.sort(sort).all();
results[listResolverName] = sortedList;
return results;
}
// console.log('// withList reducer');
// console.log('queryName: ', queryName);
// console.log('terms: ', mergedTerms);
// console.log('selector: ', selector);
// console.log('options: ', options);
// console.log('previousResults: ', previousResults);
// console.log('previous titles: ', _.pluck(previousResults[listResolverName], 'title'))
// console.log('action: ', action);
switch (action.operationName) {
case newMutationName:
// if new document belongs to current list (based on view selector), add it
const newDocument = action.result.data[newMutationName];
if (mingoQuery.test(newDocument)) {
newResults = addToResults(previousResults, newDocument);
newResults = reorderResults(newResults, options.sort);
}
// console.log('** new **')
// console.log('newDocument: ', newDocument)
// console.log('belongs to list: ', mingoQuery.test(newDocument))
break;
case editMutationName:
const editedDocument = action.result.data[editMutationName];
if (mingoQuery.test(editedDocument)) {
// edited document belongs to the list
if (!_.findWhere(previousResults[listResolverName], {_id: editedDocument._id})) {
// if document wasn't already in list, add it
newResults = addToResults(previousResults, editedDocument);
}
newResults = reorderResults(newResults, options.sort);
} else {
// if edited doesn't belong to current list anymore (based on view selector), remove it
newResults = removeFromResults(previousResults, editedDocument);
}
// console.log('** edit **')
// console.log('editedDocument: ', editedDocument)
// console.log('belongs to list: ', mingoQuery.test(editedDocument))
// console.log('exists in list: ', !!_.findWhere(previousResults[listResolverName], {_id: editedDocument._id}))
break;
case removeMutationName:
const removedDocument = action.result.data[removeMutationName];
newResults = removeFromResults(previousResults, removedDocument);
// console.log('** remove **')
// console.log('removedDocument: ', removedDocument)
break;
case 'vote':
// console.log('** vote **')
// reorder results in case vote changed the order
// newResults = reorderResults(newResults, options.sort);
break;
default:
// console.log('** no action **')
return previousResults;
}
// console.log('newResults: ', newResults)
// console.log('new titles: ', _.pluck(newResults[listResolverName], 'title'))
// console.log('\n\n')
// copy over arrays explicitely to ensure new sort is taken into account
return {
[listResolverName]: [...newResults[listResolverName]],
[totalResolverName]: newResults[totalResolverName],
}
}
export default withList;