Skip to content

Instantly share code, notes, and snippets.

@cdata
Last active August 19, 2017 22:48
Show Gist options
  • Save cdata/e843c599ab8b9df90e73c5d5b4646838 to your computer and use it in GitHub Desktop.
Save cdata/e843c599ab8b9df90e73c5d5b4646838 to your computer and use it in GitHub Desktop.
import { LRUCache } from './lru-cache.js';
const FirebaseQueryAction = {
snapshotReceived: 'FIREBASE_QUERY_SNAPSHOT_RECEIVED',
created: 'FIREBASE_QUERY_CREATED'
};
const FirebaseQueryActionCreatorCache = (maxRealtimeQueries = 10) => {
const cache = new LRUCache(
maxRealtimeQueries,
({ query, unsubscribe }) => unsubscribe());
const db = firebase.firestore();
return (key, queryFactory) => dispatch => {
const existingQuery = cache.get(key);
if (existingQuery == null) {
const query = queryFactory(db);
const unsubscribe = query.onSnapshot(querySnapshot => {
dispatch({
type: FirebaseQueryAction.snapshotReceived,
payload: { key, querySnapshot }
});
});
cache.set(cacheKey, { query, unsubscribe });
dispatch({
type: FirebaseQueryAction.created,
payload: { key }
});
}
};
};
const FirebaseQueriesReducer = (
state = {},
action) => {
switch(action.type) {
case FirebaseQueryAction.created:
case FirebaseQueryAction.snapshotReceived:
const { key } = action.payload;
return {
...state,
[key]: FirebaseQueryReducer(state[key], action)
};
default:
return state;
}
}
const FirebaseQueryReducer = (
state = { pending: true, items: [] },
action) => {
switch(action.type) {
default:
case FirebaseQueryAction.created:
return state;
case FirebaseQueryAction.snapshotReceived:
const { querySnapshot } = action.payload;
const { items } = state;
querySnapshot.docChanges.forEach(change => {
switch (change.type) {
case 'added':
items.splice(change.newIndex, 0, change.doc.data());
break;
case 'changed':
items.splice(change.oldIndex, 1);
items.splice(change.newIndex, 0, change.doc.data());
break;
case 'removed':
items.splice(change.oldIndex, 1);
break;
}
});
return { pending: false, items };
}
}
export {
FirebaseQueryAction,
FirebaseQueriesReducer,
FirebaseQueryActionCreatorCache
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment