-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathliveDoc.js
58 lines (46 loc) · 1.07 KB
/
liveDoc.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
import { reactive, toRefs, computed } from '@vue/composition-api'
import firebase from 'firebase/app'
import 'firebase/firestore'
import useAuth from '~/use/auth'
export default (name, id) => {
const { uid } = useAuth()
const firestore = firebase.firestore()
const state = reactive({
loading: true,
exists: false,
doc: null,
id: null
})
const collection = firestore.collection(name)
collection.doc(id).onSnapshot((doc) => {
state.loading = false
state.exists = doc.exists
if (doc.exists) {
state.doc = doc.data()
state.id = doc.id
} else {
state.doc = null
state.id = null
}
})
async function update(data) {
if (!state.exists || !state.id) {
return
}
const changes = {
updatedAt: +new Date(),
updatedBy: uid.value,
...data
}
const result = await collection.doc(id).update(changes)
return result
}
const isCreator = computed(
() => state.doc && uid.value === state.doc.createdBy
)
return {
...toRefs(state),
update,
isCreator
}
}