/
index.ts
105 lines (89 loc) · 2.56 KB
/
index.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import type { Ref } from 'vue-demi'
import { ref } from 'vue-demi'
import type { DocumentData, DocumentReference, DocumentSnapshot, Query, QueryDocumentSnapshot } from 'firebase/firestore'
import { isDef, tryOnScopeDispose } from '@vueuse/shared'
import { onSnapshot } from 'firebase/firestore'
export interface UseFirestoreOptions {
errorHandler?: (err: Error) => void
autoDispose?: boolean
}
export type FirebaseDocRef<T> =
Query<T> |
DocumentReference<T>
function getData<T>(
docRef: DocumentSnapshot<T> | QueryDocumentSnapshot<T>,
) {
const data = docRef.data()
if (data) {
Object.defineProperty(data, 'id', {
value: docRef.id.toString(),
writable: false,
})
}
return data
}
function isDocumentReference<T>(docRef: any): docRef is DocumentReference<T> {
return (docRef.path?.match(/\//g) || []).length % 2 !== 0
}
export function useFirestore<T extends DocumentData>(
docRef: DocumentReference<T>,
initialValue: T,
options?: UseFirestoreOptions
): Ref<T | null>
export function useFirestore<T extends DocumentData>(
docRef: Query<T>,
initialValue: T[],
options?: UseFirestoreOptions
): Ref<T[]>
// nullable initial values
export function useFirestore<T extends DocumentData>(
docRef: DocumentReference<T>,
initialValue?: T | undefined,
options?: UseFirestoreOptions,
): Ref<T | undefined | null>
export function useFirestore<T extends DocumentData>(
docRef: Query<T>,
initialValue?: T[],
options?: UseFirestoreOptions
): Ref<T[] | undefined>
/**
* Reactive Firestore binding. Making it straightforward to always keep your
* local data in sync with remotes databases.
*
* @see https://vueuse.org/useFirestore
* @param docRef
* @param initialValue
* @param options
*/
export function useFirestore<T extends DocumentData>(
docRef: FirebaseDocRef<T>,
initialValue: any = undefined,
options: UseFirestoreOptions = {},
) {
const {
errorHandler = (err: Error) => console.error(err),
autoDispose = true,
} = options
if (isDocumentReference<T>(docRef)) {
const data = ref(initialValue) as Ref<T | null | undefined>
const close = onSnapshot(docRef, (snapshot) => {
data.value = getData(snapshot) || null
}, errorHandler)
tryOnScopeDispose(() => {
close()
})
return data
}
else {
const data = ref(initialValue) as Ref<T[] | undefined>
const close = onSnapshot(docRef, (snapshot) => {
data.value = snapshot.docs.map(getData).filter(isDef)
}, errorHandler)
if (autoDispose) {
tryOnScopeDispose(() => {
close()
})
}
return data
}
}