Skip to content

Instantly share code, notes, and snippets.

@OlavHN
Created March 29, 2016 10:05
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save OlavHN/1958ecde348e5b87f2d6 to your computer and use it in GitHub Desktop.
redux middleware with firebase replay / remote actions
import Firebase from 'firebase';
const firebaseUrl = 'https://spatially.firebaseio.com/clients';
const timeOffsetUrl = 'https://spatially.firebaseio.com/.info/serverTimeOffset';
let ref = new Firebase(firebaseUrl);
let timeRef = new Firebase(timeOffsetUrl);
let cachedUid;
export default ({dispatch, getState}) => next => action => {
// The first action rehydrates, so now we've probably got the uid now
let result = next(action);
let { uid } = getState().info || {};
if (!uid)
return;
if (uid !== cachedUid) {
// Potentially first time!
if (cachedUid)
ref.child(cachedUid).child('actions').off();
// We make sure the event isn't old by correlating events with server time
timeRef.once('value', snap => {
let offset = snap.val();
let acceptedEventTime = Date.now() + offset;
console.log(offset)
ref.child(uid).child('actions').limitToLast(1).on('child_added', snap => {
let action = snap.val();
if (action.time && action.time + offset > acceptedEventTime) {
console.log('Running remote action', action);
dispatch(action);
} else {
console.log('got an .. old? event', action);
}
});
});
cachedUid = uid;
}
ref.child(uid).child('state').push(result);
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment