-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirestore.ts
59 lines (52 loc) · 1.47 KB
/
firestore.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
import {
doc,
DocumentData,
DocumentReference,
getDoc,
getFirestore,
setDoc,
} from "firebase/firestore";
import { ColorConfig } from "./colorConfig";
import app from "./firebase";
interface SerializedColorConfig {
colorConfigStringified: string;
}
const db = getFirestore(app);
function getColorConfigDocRef(uid: string): DocumentReference<DocumentData> {
return doc(db, "users", uid, "userConfigs", "colorConfig");
}
function serializeColorConfig(config: ColorConfig): SerializedColorConfig {
return {
colorConfigStringified: JSON.stringify(config),
};
}
function deserializeColorConfig(serializedConfig: SerializedColorConfig): ColorConfig {
return JSON.parse(serializedConfig.colorConfigStringified);
}
export function setColorConfig(
uid: string,
config: ColorConfig
): Promise<void> {
const docRef = getColorConfigDocRef(uid);
return setDoc(docRef, serializeColorConfig(config));
}
/**
* Gets the current colorConfig for a user, or sets it if it's not available
* @param uid
* @param defaultConfig
* @returns
*/
export function getColorConfig(
uid: string,
defaultConfig: ColorConfig
): Promise<ColorConfig> {
const docRef = getColorConfigDocRef(uid);
return getDoc(docRef)
.then((docSnap) => docSnap.data())
.then((colorConfig) => {
if (colorConfig) {
return deserializeColorConfig(colorConfig as SerializedColorConfig);
}
return setColorConfig(uid, defaultConfig).then(() => defaultConfig);
});
}