Skip to content

Instantly share code, notes, and snippets.

@davideast
Last active January 7, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davideast/0b5705af956d14a03fa8f35869e1efac to your computer and use it in GitHub Desktop.
Save davideast/0b5705af956d14a03fa8f35869e1efac to your computer and use it in GitHub Desktop.
Guillermo Views Transaction
/**
* Increases view count by one.
* @param: db {FirebaseDatabase} - Firebase Database instance
* @param: id {String} - id of post
* @return: Promise<{committed: boolean, snapshot: nullable firebase.database.DataSnapshot}>
* @docs: https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction
*/
const incrementViews = (db, id) => {
const ref = db.ref('views').child(id)
return ref.transaction(currentViews => {
// if it has never been set it returns null
if(currentViews === null) { currentViews = 0; }
return currentViews + 1;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment