-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
101 lines (92 loc) · 2.61 KB
/
Copy pathindex.js
File metadata and controls
101 lines (92 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import db from "./firebase.js";
import {
collection,
doc,
addDoc,
getDocs,
getDoc,
updateDoc,
deleteDoc,
terminate,
} from "firebase/firestore";
/** create */
export async function createExample() {
const docRef = await addDoc(collection(db, "users"), {
name: "Ali",
age: 25,
});
console.log(`ok, added a user doc, id is ${docRef.id}`);
return docRef.id;
}
/** read */
export async function readExample() {
const snapshot = await getDocs(collection(db, "users"));
console.log("users right now:");
snapshot.forEach((d) => {
console.log(` ${d.id}`, d.data());
});
}
/** update */
export async function updateExample(docId) {
if (!docId) {
const snapshot = await getDocs(collection(db, "users"));
if (snapshot.empty) {
console.log("users is empty, add something first");
return;
}
docId = snapshot.docs[0].id;
console.log(`you didn't pass an id, using the first doc (${docId})`);
}
const ref = doc(db, "users", docId);
await updateDoc(ref, { age: 26, updatedAt: new Date().toISOString() });
const snap = await getDoc(ref);
console.log("after patch:", snap.data());
}
/** delete */
export async function deleteExample(docId) {
if (!docId) {
const snapshot = await getDocs(collection(db, "users"));
if (snapshot.empty) {
console.log("nothing to delete");
return;
}
docId = snapshot.docs[0].id;
console.log(`no id, deleting the first one (${docId})`);
}
await deleteDoc(doc(db, "users", docId));
console.log(`deleted ${docId}`);
}
async function runAll() {
console.log("running the whole thing: create, read, update, read, delete, read\n");
const id = await createExample();
await readExample();
await updateExample(id);
await readExample();
await deleteExample(id);
await readExample();
console.log("\nall good");
}
const modes = new Set(["create", "read", "update", "delete", "all"]);
const mode = process.argv[2] ?? "all";
async function main() {
try {
if (!modes.has(mode)) {
console.log(`usage: node index.js [create|read|update|delete|all]
create fake user in users
read print users
update mess with age (pass a doc id or it grabs the first)
delete same deal
all runs the full chain, default if you pass nothing`);
process.exitCode = 1;
return;
}
if (mode === "create") await createExample();
else if (mode === "read") await readExample();
else if (mode === "update") await updateExample(process.argv[3]);
else if (mode === "delete") await deleteExample(process.argv[3]);
else await runAll();
} finally {
await terminate(db);
}
}
main();