-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollection.js
42 lines (35 loc) · 947 Bytes
/
collection.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
import Vue from 'vue'
import { toRefs, computed } from '@vue/composition-api'
import firebase from 'firebase/app'
import 'firebase/firestore'
const state = Vue.observable({})
export default (name) => {
if (!state[name]) {
const firestore = firebase.firestore()
const collection = firestore.collection(name)
Vue.set(state, name, {})
collection.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'modified' || change.type === 'added') {
Vue.set(state[name], change.doc.id, change.doc.data())
}
if (change.type === 'removed') {
Vue.delete(state[name], change.doc.id)
}
})
})
}
const docs = computed(() => {
if (!state[name]) {
return []
}
return Object.keys(state[name]).map((key) => ({
...state[name][key],
id: key
}))
})
return {
...toRefs(state[name]),
docs
}
}