Created
January 16, 2019 09:36
-
-
Save antruongnguyen/5dac6e80dbc70b567ec881d19ea18d66 to your computer and use it in GitHub Desktop.
Recap Firebase Realtime Database for Web
This file contains hidden or 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
// <script src="https://www.gstatic.com/firebasejs/5.4.0/firebase.js"></script> | |
// Initialize Firebase | |
var project_id = "FIREBASE_PROJECT_ID"; | |
var config = { | |
apiKey: "API_KEY", | |
authDomain: project_id + ".firebaseapp.com", | |
databaseURL: "https://" + project_id + ".firebaseio.com", | |
projectId: project_id, | |
storageBucket: project_id + ".appspot.com", | |
messagingSenderId: "CLOUD_MESSENGING_SENDER_ID" | |
}; | |
firebase.initializeApp(config); | |
var db = firebase.database(); | |
// Need to modify database rule for read and write permissions before going futher | |
// { | |
// "rules": { | |
// ".read": true, | |
// ".write": true, | |
// "products": { | |
// ".indexOn": ["id"] | |
// }, | |
// "categories": { | |
// ".indexOn": ["id"] | |
// } | |
// } | |
// } | |
// EXAMPLE DB | |
// my-db | |
// categories | |
// 0 | |
// "id": 1 | |
// "name: "Metal" | |
// 1 | |
// "id": 2 | |
// "name: "Plastic" | |
// products | |
// 0 | |
// "id": 1 | |
// "name": "Chair" | |
// "category: 2 | |
// 1 | |
// "id": 2 | |
// "name": "Table" | |
// "category: 1 | |
// READ using on and once | |
// on(eventType, callback, cancelCallbackOrContext, context) | |
// eventType: "value", "child_added", "child_changed", "child_removed", or "child_moved" | |
var categoriesRef = db.ref('categories'); | |
// Handle for new value: | |
categoriesRef.on('value', function(dataSnapshot) { | |
//... | |
}); | |
// Handle for new child added | |
categoriesRef.on('child_added', function(childSnapshot, prevChildKey) { | |
//... | |
}); | |
// Handle child removal: | |
categoriesRef.on('child_removed', function(oldChildSnapshot) { | |
//... | |
}); | |
// Handle child data changes: | |
categoriesRef.on('child_changed', function(childSnapshot, prevChildKey) { | |
//... | |
}); | |
// Handle child ordering changes: | |
categoriesRef.on('child_moved', function(childSnapshot, prevChildKey) { | |
//... | |
}); | |
// once(eventType, successCallback, failureCallbackOrContext, context) | |
// Read data once and won't read again when data has changed. | |
categoriesRef.once('value').then(function(dataSnapshot) { | |
// handle read data. | |
}); | |
// CREATE | |
// using set(value, onComplete) | |
// Beware of overwrite or delete the record with same KEY | |
var newCatId = db.ref().child('categories').push().key; // auto generate new UID key | |
db.ref('categories/' + newCatId).set({ | |
id: 3, | |
name: "Other" | |
}); | |
// using push(value, onComplete) will return its reference | |
// Create a new category reference with an auto-generated id | |
var newCategoryRef = categoriesRef.push(); | |
newCategoryRef.set({ | |
id: 4, | |
name: "Something" | |
}); | |
// UPDATE | |
var records = {}; | |
records['categories/1'] = {name: "Wood"}; | |
records['products/0'] = {category: 2}; | |
// Could update multiple values | |
db.ref().update(records); | |
// This action will update the name of category with key 1 and update the category of product with key 0. | |
// DELETE | |
db.ref('categories/2').remove() | |
// This action will remove the category with key 2 | |
db.ref('categories/2').set(null); | |
// Set null value to a key will delete record. It will do the same as remove() function. | |
// FIND | |
// https://firebase.google.com/docs/reference/js/firebase.database.Query | |
// https://firebase.google.com/docs/database/web/lists-of-data | |
var productsRef = db.ref('products'); | |
// Find 10 latest products | |
productsRef.limitToLast(10); | |
// You can only use one order-by method at a time. | |
// Calling an order-by method multiple times in the same query throws an error. | |
productsRef.orderByChild('id'); // data will present in order of null, false, true (key in alphabetical order), number, text, object | |
productsRef.orderByKey(); | |
productsRef.orderByValue(); | |
productsRef.orderByKey().limitToFirst(10); | |
productsRef.orderByKey().limitToLast(10); | |
productsRef.orderByChild('id').startAt(2).endAt(5); // get product records with ID in [2:5] | |
productsRef.orderByChild('id').equalTo(1); // get product with ID equals to 1 | |
// STORE DATA OFFLINE | |
// Detecting Connection State | |
var connectedRef = firebase.database().ref(".info/connected"); | |
connectedRef.on("value", function(snap) { | |
console.log((snap.val() !== true ? "not " : "") + "connected"); | |
}); | |
// Server Time | |
var userLastOnlineRef = firebase.database().ref("users/name/lastOnline"); | |
userLastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP); | |
// Server time offset | |
var offsetRef = firebase.database().ref(".info/serverTimeOffset"); | |
offsetRef.on("value", function(snap) { | |
var offset = snap.val(); | |
var estimatedServerTimeMs = new Date().getTime() + offset; | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment