-
Notifications
You must be signed in to change notification settings - Fork 0
/
Firestore.js
57 lines (50 loc) · 1.52 KB
/
Firestore.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
const firebase = require("firebase/app");
require("firebase/firestore");
require("firebase/auth");
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const firestoreSettings = process.env.FIRESTORE_EMULATOR_HOST ?
{ host: `${process.env.FIRESTORE_EMULATOR_HOST}:${process.env.FIRESTORE_EMULATOR_PORT}`,
ssl: false
} : {};
exports.connect = token => gameId => () => {
firebase.initializeApp(firebaseConfig);
firebase
.auth()
.signInWithCustomToken(token)
.catch(error => {
const { code, message } = error;
if (code === 'auth/invalid-custom-token') {
console.error('The token you provided is not valid.');
} else {
console.error(error);
}
});
const db = firebase.firestore();
db.settings(firestoreSettings);
window.firebase = firebase;
return { db, gameId: gameId.toString() };
};
exports.addCommand = obj => ({ db, gameId }) => () => {
db.collection("games")
.doc(gameId)
.collection("commands")
.add(
Object.assign(obj, {
created_at: firebase.firestore.FieldValue.serverTimestamp()
}));
};
exports.onSnapshotCommandAdd = listener => ({ db, gameId }) => () => {
db.collection("games")
.doc(gameId)
.collection("commands")
.orderBy("created_at")
.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (!change.doc.metadata.hasPendingWrites) {
if (change.type === "added") {
listener(change.doc.data())();
}
}
});
});
};