-
-
Save EECOLOR/d85e79c598484d407078a9a5307f183c to your computer and use it in GitHub Desktop.
This snippet enables to iterate over a Firebase reference in a non-blocking way. If you need to iterate over a large reference, a child_added query may block your Firebase as it will query the whole data before iteration. With this snippet, children are retrieved one by one, making it slower / safer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function throttledChildAdded(ref, callback, onError, sortChildKey = null /* uses `key` if null */) { | |
const state = { stopped: false } | |
let listener = null | |
throttledChildAdded({ state, endReached: lastSeen => { listener = listenForNewChildren({ startAfter: lastSeen }) } }) | |
return () => { | |
state.stopped = true | |
if (listener) ref.off('child_added', listener) | |
} | |
function throttledChildAdded({ state, endReached, start = null }) { | |
if (state.stopped) return | |
withStart(ref, start).limitToFirst(2).once('value', | |
snap => { | |
const atLast = snap.numChildren() < 2 | |
if (!state.stopped && atLast) endReached(start) | |
snap.forEach(snap => { | |
const sortValue = getSortValue(snap) | |
if (sortValue === start || state.stopped) return | |
callback(snap) | |
if (!atLast) setTimeout(() => throttledChildAdded({ state, endReached, start: sortValue }), 0) | |
return true // stop iteration | |
}) | |
}, | |
onError | |
) | |
} | |
function listenForNewChildren({ startAfter }) { | |
return withStart(ref, startAfter) | |
.on('child_added', | |
snap => { | |
const sortValue = getSortValue(snap) | |
if (sortValue === startAfter) return | |
callback(snap) | |
}, | |
onError | |
) | |
} | |
function getSortValue(snap) { | |
return sortChildKey ? snap.child(sortChildKey).val() : snap.key | |
} | |
function withStart(ref, start = null) { | |
const query = sortChildKey ? ref.orderByChild(sortChildKey) : ref.orderByKey() | |
return start ? query.startAt(start) : query | |
} | |
} |
Last version also allows to use other keys than key for sorting
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a modified version based on the same principle. This however is implemented using a different design (a simple function, I don't like
this
).The differences:
ref.on('child_added', ...)