-
Notifications
You must be signed in to change notification settings - Fork 32
/
firebase.ts
90 lines (71 loc) · 1.91 KB
/
firebase.ts
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
import { initializeApp } from "firebase/app";
import { doc, getFirestore, onSnapshot } from "firebase/firestore";
import { getAuth, onAuthStateChanged, type User } from "firebase/auth";
import { getStorage } from "firebase/storage";
import { writable, type Readable, derived } from "svelte/store";
const firebaseConfig = {
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const db = getFirestore();
export const auth = getAuth();
export const storage = getStorage();
/**
* @returns a store with the current firebase user
*/
function userStore() {
let unsubscribe: () => void;
if (!auth || !globalThis.window) {
console.warn('Auth is not initialized or not in browser');
const { subscribe } = writable<User | null>(null);
return {
subscribe,
}
}
const { subscribe } = writable(auth?.currentUser ?? null, (set) => {
unsubscribe = onAuthStateChanged(auth, (user) => {
set(user);
});
return () => unsubscribe();
});
return {
subscribe,
};
}
export const user = userStore();
/**
* @param {string} path document path or reference
* @param {any} startWith optional default data
* @returns a store with realtime updates on document data
*/
export function docStore<T>(
path: string,
) {
let unsubscribe: () => void;
const docRef = doc(db, path);
const { subscribe } = writable<T | null>(null, (set) => {
unsubscribe = onSnapshot(docRef, (snapshot) => {
set((snapshot.data() as T) ?? null);
});
return () => unsubscribe();
});
return {
subscribe,
ref: docRef,
id: docRef.id,
};
}
interface UserData {
username: string;
bio: string;
photoURL: string;
published: boolean;
links: any[];
}
export const userData: Readable<UserData | null> = derived(user, ($user, set) => {
if ($user) {
return docStore<UserData>(`users/${$user.uid}`).subscribe(set);
} else {
set(null);
}
});