This repository has been archived by the owner on Mar 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
collection.ts
169 lines (144 loc) · 4.97 KB
/
collection.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
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
import { HasId, OmitId, Encodable, Decodable, OptionalIdStorable, Storable, PartialStorable, QueryKey, CollectionReference, DocumentSnapshot, DocumentReference, QuerySnapshot } from './types'
import { Context } from './context'
import { Converter } from './converter'
import { Query } from './query'
export class Collection<T extends HasId, S = OmitId<T>> {
context: Context
collectionRef: CollectionReference
private converter: Converter<T, S>
constructor ({ context, path, encode, decode }: {
context: Context,
path: string,
encode?: Encodable<T, S>,
decode?: Decodable<T, S>,
}) {
this.context = context
this.collectionRef = context.firestore.collection(path)
this.converter = new Converter({ encode, decode })
}
toObject (documentSnapshot: DocumentSnapshot): T {
return this.converter.decode(documentSnapshot)
}
docRef (id?: string): DocumentReference {
if (id) return this.collectionRef.doc(id)
return this.collectionRef.doc()
}
async fetch (id: string): Promise <T | undefined> {
const docRef = this.docRef(id)
const snapshot = (this.context.tx)
? await this.context.tx.get(docRef)
: await docRef.get()
if (!snapshot.exists) return undefined
return this.toObject(snapshot)
}
async fetchAll (): Promise<T[]> {
const snapshot = (this.context.tx)
? await this.context.tx.get(this.collectionRef)
: await this.collectionRef.get()
const arr: T[] = []
snapshot.forEach((documentSnapshot) => {
arr.push(this.toObject(documentSnapshot))
})
return arr
}
async add (obj: OptionalIdStorable<T>): Promise<string> {
let docRef: DocumentReference
const doc = this.converter.encode(obj)
if (this.context.tx) {
docRef = this.docRef()
this.context.tx.set(docRef, doc)
} else if (this.context.batch) {
docRef = this.docRef()
this.context.batch.set(docRef, doc)
} else {
docRef = await this.collectionRef.add(doc)
}
return docRef.id
}
async set (obj: Storable<T>): Promise<string> {
if (!obj.id) throw new Error('Argument object must have "id" property')
const docRef = this.docRef(obj.id)
const setDoc = this.converter.encode(obj)
if (this.context.tx) {
this.context.tx.set(docRef, setDoc)
} else if (this.context.batch) {
this.context.batch.set(docRef, setDoc)
} else {
await docRef.set(setDoc)
}
return obj.id
}
addOrSet (obj: OptionalIdStorable<T>): Promise<string> {
if ('id' in obj) {
return this.set(obj as Storable<T>)
}
return this.add(obj)
}
async update (obj: PartialStorable<S & HasId>): Promise<string> {
if (!obj.id) throw new Error('Argument object must have "id" property')
const docRef = this.docRef(obj.id)
// Copy obj with exclude 'id' key
const { id, ...updateDoc } = { ...obj }
if (this.context.tx) {
this.context.tx.update(docRef, updateDoc)
} else if (this.context.batch) {
this.context.batch.update(docRef, updateDoc)
} else {
await docRef.update(updateDoc)
}
return obj.id
}
async delete (id: string): Promise<string> {
const docRef = this.docRef(id)
if (this.context.tx) {
this.context.tx.delete(docRef)
} else if (this.context.batch) {
this.context.batch.delete(docRef)
} else {
await docRef.delete()
}
return id
}
async bulkAdd (objects: Array<OptionalIdStorable<T>>): Promise<FirebaseFirestore.WriteResult[]> {
return this.context.runBatch(async () => {
for (const obj of objects) {
await this.add(obj)
}
})
}
async bulkSet (objects: Array<Storable<T>>): Promise<FirebaseFirestore.WriteResult[]> {
return this.context.runBatch(async () => {
for (const obj of objects) {
await this.set(obj)
}
})
}
async bulkDelete (docIds: string[]): Promise<FirebaseFirestore.WriteResult[]> {
return this.context.runBatch(async () => {
for (const docId of docIds) {
await this.delete(docId)
}
})
}
where (fieldPath: QueryKey<S>, opStr: FirebaseFirestore.WhereFilterOp, value: any): Query<T, S> {
const query = this.collectionRef.where(fieldPath as string | FirebaseFirestore.FieldPath, opStr, value)
return new Query<T, S>(this.converter, this.context, query)
}
orderBy (fieldPath: QueryKey<S>, directionStr?: FirebaseFirestore.OrderByDirection): Query<T, S> {
const query = this.collectionRef.orderBy(fieldPath as string | FirebaseFirestore.FieldPath, directionStr)
return new Query<T, S>(this.converter, this.context, query)
}
limit (limit: number): Query<T, S> {
const query = this.collectionRef.limit(limit)
return new Query<T, S>(this.converter, this.context, query)
}
onSnapshot (callback: (
querySnapshot: QuerySnapshot,
toObject: (documentSnapshot: DocumentSnapshot) => T
) => void
): () => void {
return this.collectionRef.onSnapshot((_querySnapshot) => {
callback(_querySnapshot, this.toObject.bind(this))
})
}
}