-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirebaseFirestoreService.js
96 lines (80 loc) · 2.16 KB
/
FirebaseFirestoreService.js
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
import {
getFirestore,
collection,
addDoc,
doc,
getDocs,
query,
where,
updateDoc,
arrayUnion,
arrayRemove,
onSnapshot
} from "firebase/firestore";
import { app } from "./FirebaseConfig";
const db = getFirestore(app);
let uid = ""
const colRef = collection(db, "users");
//const [topFive,setTopFive] =
const createUser = async (uid, username) =>
await addDoc(colRef, { id: uid, username, times: [] })
const getUserData = async(uid) => {
let userData = []
const q = query(colRef, where("id", "==", uid))
const querySnapshot = await getDocs(q)
querySnapshot.forEach((doc) => {
userData.push(doc.id)
userData.push(doc.data())
})
return userData
}
const getRealTimeUserData = (uid) => {
let userdata = []
const q = query(colRef, where("id", "==", uid))
onSnapshot(q, (snapshot) => {
snapshot.forEach((doc) => {
userdata.push(doc.id)
userdata.push(doc.data())
})
console.log(userdata)
return userdata
})
//unsub()
}
const getHallofFame = async() => {
const querySnapshot = await getDocs(colRef)
let times_array = []
let usernames_array = []
querySnapshot.forEach((doc) => {
const sortedTimes = doc.data().times.sort()
const username = doc.data().username
times_array.push(sortedTimes)
usernames_array.push(username)
})
const topResults = times_array.map((el,i) => [...[el[0],usernames_array[i]]])
const sortedTopResults = topResults.sort().slice(0,15)
return sortedTopResults
}
const updateResults = async (finalTime,docId) => {
const id = !docId ? 'DyzOpTPS6YczIxTXMnMn' : docId
const docRef = doc(colRef,id)
updateDoc(docRef , {
times: arrayUnion(finalTime)
})
}
const removeWorstTime = (worstTime,docId) => {
const id = !docId ? 'DyzOpTPS6YczIxTXMnMn' : docId
const docRef = doc(colRef,id)
updateDoc(docRef , {
times: arrayRemove(worstTime)
})
}
const FirebaseFirestoreService = {
createUser,
getUserData,
getRealTimeUserData,
updateResults,
removeWorstTime,
getHallofFame
};
export default FirebaseFirestoreService;