forked from prescottprue/react-redux-firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.js
393 lines (368 loc) · 12 KB
/
helpers.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import {
size,
map,
some,
first,
drop,
mapValues,
reduce,
isString,
defaultsDeep
} from 'lodash'
import { getPopulateObjs } from './utils/populate'
import { metaParams, paramSplitChar } from './constants'
/**
* @description Detect whether items are loaded yet or not
* @param {Object} item - Item to check loaded status of. A comma seperated list is also acceptable.
* @return {Boolean} Whether or not item is loaded
* @example
* import React, { Component, PropTypes } from 'react'
* import { connect } from 'react-redux'
* import { firebaseConnect, isLoaded, dataToJS } from 'react-redux-firebase'
*
* @firebaseConnect(['/todos'])
* @connect(
* ({ firebase }) => ({
* todos: dataToJS(firebase, '/todos'),
* })
* )
* class Todos extends Component {
* static propTypes = {
* todos: PropTypes.object
* }
*
* render() {
* const { todos } = this.props;
*
* // Show loading while todos are loading
* if(!isLoaded(todos)) {
* return <span>Loading...</span>
* }
*
* return <ul>{todosList}</ul>
* }
* }
*/
export const isLoaded = function () {
if (!arguments || !arguments.length) {
return true
}
return map(arguments, a => a !== undefined).reduce((a, b) => a && b)
}
/**
* @description Detect whether items are empty or not
* @param {Object} item - Item to check loaded status of. A comma seperated list is also acceptable.
* @return {Boolean} Whether or not item is empty
* @example
* import React, { Component, PropTypes } from 'react'
* import { connect } from 'react-redux'
* import { firebaseConnect, isEmpty, dataToJS } from 'react-redux-firebase'
*
* @firebaseConnect(['/todos'])
* @connect(
* ({ firebase }) => ({
* todos: dataToJS(firebase, '/todos'),
* })
* )
* class Todos extends Component {
* static propTypes = {
* todos: PropTypes.object
* }
*
* render() {
* const { todos } = this.props;
*
* // Message for if todos are empty
* if(isEmpty(todos)) {
* return <span>No Todos Found</span>
* }
*
* return <ul>{todosList}</ul>
* }
* }
*/
export const isEmpty = data => !(data && size(data))
/**
* @description Fix path by adding "/" to path if needed
* @param {String} path - Path string to fix
* @return {String} - Fixed path
* @private
*/
export const fixPath = path =>
((path.substring(0, 1) === '/') ? '' : '/') + path
/**
* @description Convert Immutable Map to a Javascript object
* @param {Object} data - Immutable Map to be converted to JS object (state.firebase)
* @return {Object} data - Javascript version of Immutable Map
* @return {Object} Data located at path within Immutable Map
*/
export const toJS = data =>
data && data.toJS
? data.toJS()
: data
/**
* @description Convert parameter from Immutable Map to a Javascript object
* @param {Map} firebase - Immutable Map to be converted to JS object (state.firebase)
* @param {String} path - Path from state.firebase to convert to JS object
* @param {Object|String|Boolean} notSetValue - Value to use if data is not available
* @return {Object} Data located at path within Immutable Map
* @example <caption>Basic</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, pathToJS } from 'react-redux-firebase'
*
* @firebaseConnect()
* @connect(({ firebase }) => ({
* profile: pathToJS(firebase, 'profile'),
* auth: pathToJS(firebase, 'auth')
* })
* export default class MyComponent extends Component {
* ...
*/
export const pathToJS = (data, path, notSetValue) => {
if (!data) {
return notSetValue
}
const pathArr = fixPath(path).split(/\//).slice(1)
if (data.getIn) {
// Handle meta params (stored by string key)
if (some(metaParams, (v) => pathArr.indexOf(v) !== -1)) {
return toJS(
data.getIn([
first(pathArr),
drop(pathArr).join(paramSplitChar)
], notSetValue)
)
}
return toJS(data.getIn(pathArr, notSetValue))
}
return data
}
/**
* @description Convert parameter under "data" path of Immutable Map to a Javascript object.
* **NOTE:** Setting a default value will cause `isLoaded` to always return true
* @param {Map} firebase - Immutable Map to be converted to JS object (state.firebase)
* @param {String} path - Path of parameter to load
* @param {Object|String|Boolean} notSetValue - Value to return if value is not
* found in redux. This will cause `isLoaded` to always return true (since
* value is set from the start).
* @return {Object} Data located at path within Immutable Map
* @example <caption>Basic</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, dataToJS } from 'react-redux-firebase'
*
* @firebaseConnect(['/todos'])
* @connect(({ firebase }) => ({
* // this.props.todos loaded from state.firebase.data.todos
* todos: dataToJS(firebase, 'todos')
* })
* @example <caption>Default Value</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, dataToJS } from 'react-redux-firebase'
* const defaultValue = {
* 1: {
* text: 'Example Todo'
* }
* }
* @firebaseConnect(['/todos'])
* @connect(({ firebase }) => ({
* // this.props.todos loaded from state.firebase.data.todos
* todos: dataToJS(firebase, 'todos', defaultValue)
* })
*/
export const dataToJS = (data, path, notSetValue) => {
if (!data) {
return notSetValue
}
const pathArr = `/data${fixPath(path)}`.split(/\//).slice(1)
if (data.getIn) {
return toJS(data.getIn(pathArr, notSetValue))
}
return data
}
/**
* @description Convert parameter under "ordered" path of Immutable Map to a
* Javascript array. This preserves order set by query.
* @param {Map} firebase - Immutable Map to be converted to JS object (state.firebase)
* @param {String} path - Path of parameter to load
* @param {Object|String|Boolean} notSetValue - Value to return if value is not found
* @return {Object} Data located at path within Immutable Map
* @example <caption>Basic</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, orderedToJS } from 'react-redux-firebase'
*
* @firebaseConnect([
* {
* path: 'todos',
* queryParams: ['orderByChild=text'] // order alphabetically based on text
* },
* ])
* @connect(({ firebase }) => ({
* // this.props.todos loaded from state.firebase.ordered.todos
* todos: orderedToJS(firebase, 'todos')
* })
*/
export const orderedToJS = (data, path, notSetValue) => {
if (!data) {
return notSetValue
}
const pathArr = `/ordered${fixPath(path)}`.split(/\//).slice(1)
if (data.getIn) {
return toJS(data.getIn(pathArr, notSetValue))
}
return data
}
/**
* @private
* @description Build child list based on populate
* @param {Map} data - Immutable Map to be converted to JS object (state.firebase)
* @param {Object} list - Path of parameter to load
* @param {Object} populate - Object with population settings
*/
export const buildChildList = (data, list, p) =>
mapValues(list, (val, key) => {
let getKey = val
// Handle key: true lists
if (val === true) {
getKey = key
}
const pathString = p.childParam
? `${p.root}/${getKey}/${p.childParam}`
: `${p.root}/${getKey}`
// Set to child under key if populate child exists
if (dataToJS(data, pathString)) {
return p.keyProp
? { [p.keyProp]: getKey, ...dataToJS(data, pathString) }
: dataToJS(data, pathString)
}
// Populate child does not exist
return val === true ? val : getKey
})
/**
* @description Convert parameter under "data" path of Immutable Map to a
* Javascript object with parameters populated based on populates array
* @param {Map} firebase - Immutable Map to be converted to JS object (state.firebase)
* @param {String} path - Path of parameter to load
* @param {Array} populates - Array of populate objects
* @param {Object|String|Boolean} notSetValue - Value to return if value is not found
* @return {Object} Data located at path within Immutable Map
* @example <caption>Basic</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, helpers } from 'react-redux-firebase'
* const { dataToJS } = helpers
* const populates = [{ child: 'owner', root: 'users' }]
*
* const fbWrapped = firebaseConnect([
* { path: '/todos', populates } // load "todos" and matching "users" to redux
* ])(App)
*
* export default connect(({ firebase }) => ({
* // this.props.todos loaded from state.firebase.data.todos
* // each todo has child 'owner' populated from matching uid in 'users' root
* // for loading un-populated todos use dataToJS(firebase, 'todos')
* todos: populatedDataToJS(firebase, 'todos', populates),
* }))(fbWrapped)
*/
export const populatedDataToJS = (data, path, populates, notSetValue) => {
if (!data) {
return notSetValue
}
// Handle undefined child
if (!dataToJS(data, path, notSetValue)) {
return dataToJS(data, path, notSetValue)
}
const populateObjs = getPopulateObjs(populates)
// reduce array of populates to object of combined populated data
return reduce(
map(populateObjs, (p, obj) => {
// single item with iterable child
if (dataToJS(data, path)[p.child]) {
// populate child is key
if (isString(dataToJS(data, path)[p.child])) {
const key = dataToJS(data, path)[p.child]
const pathString = p.childParam
? `${p.root}/${key}/${p.childParam}`
: `${p.root}/${key}`
if (dataToJS(data, pathString)) {
return {
[p.child]: p.keyProp
? { [p.keyProp]: key, ...dataToJS(data, pathString) }
: dataToJS(data, pathString)
}
}
// matching child does not exist
return dataToJS(data, path)
}
return {
[p.child]: buildChildList(data, dataToJS(data, path)[p.child], p)
}
}
// list with child param in each item
return mapValues(dataToJS(data, path), (child, i) => {
// no matching child parameter
if (!child || !child[p.child]) {
return child
}
// populate child is key
if (isString(child[p.child])) {
const key = child[p.child]
const pathString = p.childParam
? `${p.root}/${key}/${p.childParam}`
: `${p.root}/${key}`
if (dataToJS(data, pathString)) {
return {
[p.child]: p.keyProp
? { [p.keyProp]: key, ...dataToJS(data, pathString) }
: dataToJS(data, pathString)
}
}
// matching child does not exist
return child
}
// populate child list
return {
[p.child]: buildChildList(data, child[p.child], p)
}
})
}),
// combine data from all populates to one object starting with original data
(obj, v) => defaultsDeep(v, obj), dataToJS(data, path))
}
/**
* @description Load custom object from within store
* @param {Map} firebase - Immutable Map to be converted to JS object (state.firebase)
* @param {String} path - Path of parameter to load
* @param {String} customPath - Part of store from which to load
* @param {Object|String|Boolean} notSetValue - Value to return if value is not found
* @return {Object} Data located at path within state
* @example <caption>Basic</caption>
* import { connect } from 'react-redux'
* import { firebaseConnect, helpers } from 'react-redux-firebase'
* const { customToJS } = helpers
*
* const fbWrapped = firebaseConnect(['/todos'])(App)
*
* export default connect(({ firebase }) => ({
* // this.props.todos loaded from state.firebase.data.todos
* requesting: customToJS(firebase, 'todos', 'requesting')
* }))(fbWrapped)
*/
export const customToJS = (data, path, custom, notSetValue) => {
if (!data) {
return notSetValue
}
const pathArr = `/${custom}${fixPath(path)}`.split(/\//).slice(1)
if (data.getIn) {
return toJS(data.getIn(pathArr, notSetValue))
}
return data
}
export default {
toJS,
pathToJS,
dataToJS,
orderedToJS,
populatedDataToJS,
customToJS,
isLoaded,
isEmpty
}