Skip to content

Instantly share code, notes, and snippets.

@moosebay
Last active April 23, 2018 17:36
Show Gist options
  • Save moosebay/17ecc6ff15f4aefc08e4a8fe994b8689 to your computer and use it in GitHub Desktop.
Save moosebay/17ecc6ff15f4aefc08e4a8fe994b8689 to your computer and use it in GitHub Desktop.
Firebase nodejs admin fanout with Salada objects and GeoFire
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.database().ref();
// Salada uses versions to help you structure your
// new design in other version object
const version = 'v1/';
exports.fanoutPost = functions.database.ref(version + "post/{postId}")
.onWrite(event => {
const postId = event.params.postId;
console.log('event', event);
let data = event.data.previous.val(); // the post before changes
let newData = event.data.val(); // updated post
// you can make these if else statements one line, if you want to
// I have done this way, maybe because you need to do extra work
// based on actions
// when a post is deleted
if(!event.data.exists()) {
console.log('deleted part');
fanout(postId, data, newData)
}
// when a post is updated
else if (event.data.previous.exists()) {
console.log('updated part');
fanout(postId, data, newData)
}
// when new post is created
else{
console.log('added part');
fanout(postId, newData, newData)
}
});
function fanout(postId, data, newData){
var dataToPost = dataToFanout(postId, data, newData)
db.update(dataToPost, function(error){
console.log('delete error',error);
});
}
function dataToFanout(postId, data, newData) {
var fannedOutData = {};
fannedOutData[version + 'userPost/' + data.userId + '/' + postId] = newData;
fannedOutData[version + 'cityPost/' + data.country + '/' + data.city + ' ' + data.state + '/' + data.sportType + '/' + postId] = newData;
// if the event is deletion then delete the geofire objects
if(newData == null){
fannedOutData[version + 'postLocation/' + postId] = newData;
}
console.log('fanout data ', fannedOutData);
return fannedOutData;
}
@moosebay
Copy link
Author

Fanout is pretty important on Firebase if you want to query more than one field. Here you can find fanout example. This covers updating, deleting and creating. I have used salada objects for data crud operations you can find it here. I hope this could help you since there is no example on fanout on firebase nodejs functions (server side).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment