Skip to content

Commit db0ad0d

Browse files
committed
Add Database snippets
1 parent 798d73f commit db0ad0d

25 files changed

+658
-1
lines changed

database-next/emulator-suite.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// [SNIPPET_REGISTRY disabled]
2+
// [SNIPPETS_SEPARATION enabled]
3+
4+
import { initializeApp } from "firebase/app";
5+
6+
const firebaseApp = initializeApp({
7+
apiKey: '### FIREBASE API KEY ###',
8+
appId: '### FIREBASE APP ID ###',
9+
projectId: '### FIREBASE PROJECT ID ###'
10+
});
11+
12+
function onDocumentReady() {
13+
// [START rtdb_emulator_connect]
14+
const { getDatabase } = require("firebase/database");
15+
16+
const db = getDatabase(firebaseApp);
17+
if (location.hostname === "localhost") {
18+
// Point to the RTDB emulator running on localhost.
19+
db.useEmulator("localhost", 9000);
20+
}
21+
// [END rtdb_emulator_connect]
22+
}
23+
24+
function flushRealtimeDatabase() {
25+
// [START rtdb_emulator_flush]
26+
const { getDatabase } = require("firebase/database");
27+
28+
// With a database Reference, write null to clear the database.
29+
const db = getDatabase(firebaseApp);
30+
db.ref().set(null);
31+
// [END rtdb_emulator_flush]
32+
}

database-next/index.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// [SNIPPET_REGISTRY disabled]
2+
// [SNIPPETS_SEPARATION enabled]
3+
4+
import { initializeApp } from "firebase/app";
5+
6+
const firebaseApp = initializeApp({
7+
apiKey: '### FIREBASE API KEY ###',
8+
appId: '### FIREBASE APP ID ###',
9+
projectId: '### FIREBASE PROJECT ID ###'
10+
});
11+
12+
function getReference() {
13+
// [START rtdb_get_reference]
14+
const { getDatabase } = require("firebase/database");
15+
16+
const database = getDatabase(firebaseApp);
17+
// [END rtdb_get_reference]
18+
}

database-next/lists-of-data.js

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// [SNIPPET_REGISTRY disabled]
2+
// [SNIPPETS_SEPARATION enabled]
3+
4+
import { initializeApp } from "firebase/app";
5+
6+
const firebaseApp = initializeApp({
7+
apiKey: '### FIREBASE API KEY ###',
8+
appId: '### FIREBASE APP ID ###',
9+
projectId: '### FIREBASE PROJECT ID ###'
10+
});
11+
12+
function socialPush() {
13+
// [START rtdb_social_push]
14+
const { getDatabase } = require("firebase/database");
15+
16+
// Create a new post reference with an auto-generated id
17+
const db = getDatabase(firebaseApp);
18+
const postListRef = db.ref('posts');
19+
const newPostRef = postListRef.push();
20+
newPostRef.set({
21+
// ...
22+
});
23+
// [END rtdb_social_push]
24+
}
25+
26+
function socialListenChildren() {
27+
const postElement = document.querySelector("#post");
28+
const postId = "1234";
29+
function addCommentElement(el, key, text, author) {}
30+
function setCommentValues(el, key, text, author) {};
31+
function deleteComment(el, key) {};
32+
33+
// [START rtdb_social_listen_children]
34+
const { getDatabase } = require("firebase/database");
35+
36+
const db = getDatabase(firebaseApp);
37+
const commentsRef = db.ref('post-comments/' + postId);
38+
commentsRef.on('child_added', (data) => {
39+
addCommentElement(postElement, data.key, data.val().text, data.val().author);
40+
});
41+
42+
commentsRef.on('child_changed', (data) => {
43+
setCommentValues(postElement, data.key, data.val().text, data.val().author);
44+
});
45+
46+
commentsRef.on('child_removed', (data) => {
47+
deleteComment(postElement, data.key);
48+
});
49+
// [END rtdb_social_listen_children]
50+
}
51+
52+
function socialListenValue() {
53+
54+
// [START rtdb_social_listen_value]
55+
const { getDatabase } = require("firebase/database");
56+
57+
const db = getDatabase(firebaseApp);
58+
const ref = db.ref('/a/b/c');
59+
60+
ref.once('value', (snapshot) => {
61+
snapshot.forEach((childSnapshot) => {
62+
const childKey = childSnapshot.key;
63+
const childData = childSnapshot.val();
64+
// ...
65+
});
66+
});
67+
// [END rtdb_social_listen_value]
68+
}
69+
70+
function socialMostStarred() {
71+
// [START rtdb_social_most_starred]
72+
const { getDatabase } = require("firebase/database");
73+
const { getAuth } = require("firebase/auth");
74+
75+
const db = getDatabase(firebaseApp);
76+
const auth = getAuth(firebaseApp);
77+
78+
const myUserId = auth.currentUser.uid;
79+
const topUserPostsRef = db.ref('user-posts/' + myUserId).orderByChild('starCount');
80+
// [END rtdb_social_most_starred]
81+
}
82+
83+
function socialMostViewed() {
84+
// [START rtdb_social_most_viewed]
85+
const { getDatabase } = require("firebase/database");
86+
87+
const db = getDatabase(firebaseApp);
88+
const mostViewedPosts = db.ref('posts').orderByChild('metrics/views');
89+
// [END rtdb_social_most_viewed]
90+
}
91+
92+
function socialRecent() {
93+
// [START rtdb_social_recent]
94+
const { getDatabase } = require("firebase/database");
95+
96+
const db = getDatabase(firebaseApp);
97+
const recentPostsRef = db.ref('posts').limitToLast(100);
98+
// [END rtdb_social_recent]
99+
}

database-next/package.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"name": "database-next",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"compile": "cp ../tsconfig.json.template ./tsconfig.json && tsc"
6+
},
7+
"license": "Apache-2.0",
8+
"dependencies": {
9+
"firebase": "exp"
10+
}
11+
}

database-next/read-and-write.js

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
// [SNIPPET_REGISTRY disabled]
2+
// [SNIPPETS_SEPARATION enabled]
3+
4+
import { initializeApp } from "firebase/app";
5+
6+
const firebaseApp = initializeApp({
7+
apiKey: '### FIREBASE API KEY ###',
8+
appId: '### FIREBASE APP ID ###',
9+
projectId: '### FIREBASE PROJECT ID ###'
10+
});
11+
12+
function writeUserData_wrapped() {
13+
// [START rtdb_write_new_user]
14+
const { getDatabase } = require("firebase/database");
15+
16+
function writeUserData(userId, name, email, imageUrl) {
17+
const db = getDatabase(firebaseApp);
18+
db.ref('users/' + userId).set({
19+
username: name,
20+
email: email,
21+
profile_picture : imageUrl
22+
});
23+
}
24+
// [END rtdb_write_new_user]
25+
}
26+
27+
28+
function writeUserDataWithCompletion(userId, name, email, imageUrl) {
29+
// [START rtdb_write_new_user_completion]
30+
const { getDatabase } = require("firebase/database");
31+
32+
const db = getDatabase(firebaseApp);
33+
db.ref('users/' + userId).set({
34+
username: name,
35+
email: email,
36+
profile_picture : imageUrl
37+
}, (error) => {
38+
if (error) {
39+
// The write failed...
40+
} else {
41+
// Data saved successfully!
42+
}
43+
});
44+
// [END rtdb_write_new_user_completion]
45+
}
46+
47+
function socialListenStarCount() {
48+
const postElement = document.querySelector('#post');
49+
const postId = "1234";
50+
function updateStarCount(a, b) {
51+
// ...
52+
}
53+
54+
// [START rtdb_social_listen_star_count]
55+
const { getDatabase } = require("firebase/database");
56+
57+
const db = getDatabase(firebaseApp);
58+
const starCountRef = db.ref('posts/' + postId + '/starCount');
59+
starCountRef.on('value', (snapshot) => {
60+
const data = snapshot.val();
61+
updateStarCount(postElement, data);
62+
});
63+
// [END rtdb_social_listen_star_count]
64+
}
65+
66+
function socialSingleValueRead() {
67+
// [START rtdb_social_single_value_read]
68+
const { getDatabase } = require("firebase/database");
69+
const { getAuth } = require("firebase/auth");
70+
71+
const db = getDatabase(firebaseApp);
72+
const auth = getAuth(firebaseApp);
73+
74+
const userId = auth.currentUser.uid;
75+
return db.ref('/users/' + userId).once('value').then((snapshot) => {
76+
const username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
77+
// ...
78+
});
79+
// [END rtdb_social_single_value_read]
80+
}
81+
82+
function writeNewPost_wrapped() {
83+
const { getDatabase } = require("firebase/database");
84+
85+
// [START rtdb_social_write_fan_out]
86+
function writeNewPost(uid, username, picture, title, body) {
87+
const db = getDatabase(firebaseApp);
88+
89+
// A post entry.
90+
const postData = {
91+
author: username,
92+
uid: uid,
93+
body: body,
94+
title: title,
95+
starCount: 0,
96+
authorPic: picture
97+
};
98+
99+
// Get a key for a new Post.
100+
const newPostKey = db.ref().child('posts').push().key;
101+
102+
// Write the new post's data simultaneously in the posts list and the user's post list.
103+
const updates = {};
104+
updates['/posts/' + newPostKey] = postData;
105+
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
106+
107+
return db.ref().update(updates);
108+
}
109+
// [END rtdb_social_write_fan_out]
110+
}
111+
112+
function socialCompletionCallback() {
113+
const userId = "123";
114+
const email = "[email protected]";
115+
const imageUrl = "https://example.com/image.png";
116+
117+
// [START rtdb_social_completion_callback]
118+
const { getDatabase } = require("firebase/database");
119+
120+
const db = getDatabase(firebaseApp);
121+
db.ref('users/' + userId).set({
122+
username: name,
123+
email: email,
124+
profile_picture : imageUrl
125+
}, (error) => {
126+
if (error) {
127+
// The write failed...
128+
} else {
129+
// Data saved successfully!
130+
}
131+
});
132+
// [END rtdb_social_completion_callback]
133+
}
134+
135+
function toggleStar_wrapped() {
136+
// [START rtdb_social_star_transaction]
137+
const { getDatabase } = require("firebase/database");
138+
139+
function toggleStar(uid) {
140+
const db = getDatabase(firebaseApp);
141+
const postRef = db.ref('/posts/foo-bar-123');
142+
143+
postRef.transaction((post) => {
144+
if (post) {
145+
if (post.stars && post.stars[uid]) {
146+
post.starCount--;
147+
post.stars[uid] = null;
148+
} else {
149+
post.starCount++;
150+
if (!post.stars) {
151+
post.stars = {};
152+
}
153+
post.stars[uid] = true;
154+
}
155+
}
156+
return post;
157+
});
158+
}
159+
// [END rtdb_social_star_transaction]
160+
}
161+

database-next/sharding.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// [SNIPPET_REGISTRY disabled]
2+
// [SNIPPETS_SEPARATION enabled]
3+
4+
import { initializeApp } from "firebase/app";
5+
6+
const firebaseApp = initializeApp({
7+
apiKey: '### FIREBASE API KEY ###',
8+
appId: '### FIREBASE APP ID ###',
9+
projectId: '### FIREBASE PROJECT ID ###'
10+
});
11+
12+
function multipleInstances() {
13+
// [START rtdb_multiple_instances]
14+
const { initializeApp } = require("firebase/app");
15+
const { getDatabase } = require("firebase/database");
16+
17+
const app1 = initializeApp({
18+
databaseURL: "https://testapp-1234-1.firebaseio.com"
19+
});
20+
21+
const app2 = initializeApp({
22+
databaseURL: "https://testapp-1234-2.firebaseio.com"
23+
}, 'app2');
24+
25+
// Get the default database instance for an app1
26+
const database1 = getDatabase(app1);
27+
28+
// Get a database instance for app2
29+
const database2 = getDatabase(app2);
30+
// [END rtdb_multiple_instances]
31+
}

database/read-and-write.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function writeUserDataWithCompletion(userId, name, email, imageUrl) {
2727
// Data saved successfully!
2828
}
2929
});
30-
// [START rtdb_write_new_user_completion]
30+
// [END rtdb_write_new_user_completion]
3131
}
3232

3333
function socialListenStarCount() {

lerna.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"auth",
77
"auth-next",
88
"database",
9+
"database-next",
910
"firebaseapp",
1011
"firestore",
1112
"firestore-next",
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// This snippet file was generated by processing the source file:
2+
// ./database-next/emulator-suite.js
3+
//
4+
// To make edits to the snippets in this file, please edit the source
5+
6+
// [START rtdb_emulator_connect_modular]
7+
import { getDatabase } from "firebase/database";
8+
9+
const db = getDatabase(firebaseApp);
10+
if (location.hostname === "localhost") {
11+
// Point to the RTDB emulator running on localhost.
12+
db.useEmulator("localhost", 9000);
13+
}
14+
// [END rtdb_emulator_connect_modular]

0 commit comments

Comments
 (0)