-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
converter.ts
58 lines (48 loc) · 1.42 KB
/
converter.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
import { Timestamp } from "firebase/firestore"
import type {
FirestoreDataConverter,
QueryDocumentSnapshot,
WithFieldValue,
} from "firebase/firestore"
const isTimestamp = (value: unknown): value is Timestamp =>
typeof value === "object" && value !== null && value instanceof Timestamp
interface GetConverterOptions {
excludeId?: boolean
}
export const getConverter = <Document extends Record<string, unknown>>(
options?: GetConverterOptions
): FirestoreDataConverter<Document> => ({
// `PartialWithFieldValue` implicitly types `object` as `any`, so we want to explicitly type it
toFirestore(object: WithFieldValue<Document>) {
const document: Record<string, unknown> = {}
Object.keys(object).forEach((key) => {
if (object[key] !== undefined) {
document[key] = object[key]
}
})
return document
},
// We need to explicitly type `snapshot` since it uses `DocumentData` for generic type
fromFirestore(snapshot: QueryDocumentSnapshot<Document>) {
if (!snapshot.exists()) {
return snapshot
}
let document: Document = snapshot.data()
if (!options?.excludeId) {
document = {
...document,
id: snapshot.id,
}
}
for (const key in document) {
const value = document[key]
if (isTimestamp(value)) {
document = {
...document,
[key]: value.toDate(),
}
}
}
return document
},
})