forked from ecclouky/ecc-mp3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
200 lines (178 loc) · 5.17 KB
/
db.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import {
useQuery,
hashQueryKey,
QueryClient,
QueryClientProvider as QueryClientProviderBase,
} from "react-query";
import {
getFirestore,
onSnapshot,
doc,
collection,
query,
where,
orderBy,
getDoc,
setDoc,
updateDoc,
addDoc,
deleteDoc,
serverTimestamp,
} from "firebase/firestore";
import { firebaseApp } from "./firebase";
// Initialize Firestore
const db = getFirestore(firebaseApp);
// React Query client
const client = new QueryClient();
/**** USERS ****/
// Subscribe to user data
// Note: This is called automatically in `auth.js` and data is merged into `auth.user`
export function useUser(uid) {
// Manage data fetching with React Query: https://react-query.tanstack.com/overview
return useQuery(
// Unique query key: https://react-query.tanstack.com/guides/query-keys
["user", { uid }],
// Firestore query function that subscribes to data and auto-updates the query cache
createQuery(() => doc(db, "users", uid)),
// Only call query function if we have a `uid`
{ enabled: !!uid }
);
}
// Create a new user
export function createUser(uid, data) {
return setDoc(doc(db, "users", uid), data, { merge: true });
}
// Update an existing user
export function updateUser(uid, data) {
return updateDoc(doc(db, "users", uid), data);
}
/**** ITEMS ****/
/* Example query functions (modify to your needs) */
// Subscribe to item data
export function useItem(id) {
return useQuery(
["item", { id }],
createQuery(() => doc(db, "items", id)),
{ enabled: !!id }
);
}
// Fetch item data once
export function useItemOnce(id) {
return useQuery(
["item", { id }],
// When fetching once there is no need to use `createQuery` to setup a subscription
// Just fetch normally using `getDoc` so that we return a promise
() => getDoc(doc(db, "items", id)).then(format),
{ enabled: !!id }
);
}
// Fetch item data once (non-hook)
// Useful if you need to fetch data from outside of a component
export function getItem(id) {
return getDoc(doc(db, "items", id)).then(format);
}
// Subscribe to all items by owner
export function useItemsByOwner(owner) {
return useQuery(
["items", { owner }],
createQuery(() =>
query(
collection(db, "items"),
where("owner", "==", owner),
orderBy("createdAt", "desc")
)
),
{ enabled: !!owner }
);
}
// Create a new item
export function createItem(data) {
return addDoc(collection(db, "items"), {
...data,
createdAt: serverTimestamp(),
});
}
// Update an item
export function updateItem(id, data) {
return updateDoc(doc(db, "items", id), data);
}
// Delete an item
export function deleteItem(id) {
return deleteDoc(doc(db, "items", id));
}
/**** HELPERS ****/
// Store Firestore unsubscribe functions
const unsubs = {};
function createQuery(getRef) {
// Create a query function to pass to `useQuery`
return async ({ queryKey }) => {
let unsubscribe;
let firstRun = true;
// Wrap `onSnapshot` with a promise so that we can return initial data
const data = await new Promise((resolve, reject) => {
unsubscribe = onSnapshot(
getRef(),
// Success handler resolves the promise on the first run.
// For subsequent runs we manually update the React Query cache.
(response) => {
const data = format(response);
if (firstRun) {
firstRun = false;
resolve(data);
} else {
client.setQueryData(queryKey, data);
}
},
// Error handler rejects the promise on the first run.
// We can't manually trigger an error in React Query, so on a subsequent runs we
// invalidate the query so that it re-fetches and rejects if error persists.
(error) => {
if (firstRun) {
firstRun = false;
reject(error);
} else {
client.invalidateQueries(queryKey);
}
}
);
});
// Unsubscribe from an existing subscription for this `queryKey` if one exists
// Then store `unsubscribe` function so it can be called later
const queryHash = hashQueryKey(queryKey);
unsubs[queryHash] && unsubs[queryHash]();
unsubs[queryHash] = unsubscribe;
return data;
};
}
// Automatically remove Firestore subscriptions when all observing components have unmounted
client.queryCache.subscribe(({ type, query }) => {
if (
type === "observerRemoved" &&
query.getObserversCount() === 0 &&
unsubs[query.queryHash]
) {
// Call stored Firestore unsubscribe function
unsubs[query.queryHash]();
delete unsubs[query.queryHash];
}
});
// Format Firestore response
function format(response) {
// Converts doc into object that contains data and `doc.id`
const formatDoc = (doc) => ({ id: doc.id, ...doc.data() });
if (response.docs) {
// Handle a collection of docs
return response.docs.map(formatDoc);
} else {
// Handle a single doc
return response.exists() ? formatDoc(response) : null;
}
}
// React Query context provider that wraps our app
export function QueryClientProvider(props) {
return (
<QueryClientProviderBase client={client}>
{props.children}
</QueryClientProviderBase>
);
}