Created
March 29, 2016 10:05
-
-
Save OlavHN/1958ecde348e5b87f2d6 to your computer and use it in GitHub Desktop.
redux middleware with firebase replay / remote actions
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
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