-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFire.js
executable file
·105 lines (88 loc) · 2.57 KB
/
Fire.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
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
import uuid from 'uuid';
import getUserInfo from './utils/getUserInfo';
import shrinkImageAsync from './utils/shrinkImageAsync';
import uploadPhoto from './utils/uploadPhoto';
const firebase = require('firebase');
require('firebase/firestore');
const collectionName = 'car-oof-collection';
const firebaseConfig = {
apiKey: "AIzaSyDI4ZJ7k1eOkkDgYVe2XKy4jHDBrcOR6U0",
authDomain: "car-oof.firebaseapp.com",
databaseURL: "https://car-oof.firebaseio.com",
projectId: "car-oof",
storageBucket: "car-oof.appspot.com",
messagingSenderId: "12720290845",
appId: "1:12720290845:web:9522f970551346c45c9af4"
};
class Fire {
constructor() {
firebase.initializeApp(firebaseConfig);
firebase.firestore().settings({ timestampsInSnapshots: true });
firebase.auth().onAuthStateChanged(async user => {
if (!user) {
await firebase.auth().signInAnonymously();
}
});
}
getPaged = async ({ size, start }) => {
let ref = this.collection.orderBy('timestamp', 'desc').limit(size);
try {
if (start) {
ref = ref.startAfter(start);
}
const querySnapshot = await ref.get();
const data = [];
querySnapshot.forEach(function(doc) {
if (doc.exists) {
const post = doc.data() || {};
const user = post.user || {};
const name = user.deviceName;
const reduced = {
key: doc.id,
name: (name || 'Happy Duck').trim(),
...post,
};
data.push(reduced);
}
});
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
return { data, cursor: lastVisible };
} catch ({ message }) {
alert(message);
}
};
uploadPhotoAsync = async uri => {
const path = `${collectionName}/${this.uid}/${uuid.v4()}.jpg`;
return uploadPhoto(uri, path);
};
post = async ({ text, image: localUri }) => {
try {
const { uri: reducedImage, width, height } = await shrinkImageAsync(
localUri,
);
const remoteUri = await this.uploadPhotoAsync(reducedImage);
this.collection.add({
text,
uid: this.uid,
timestamp: this.timestamp,
imageWidth: width,
imageHeight: height,
image: remoteUri,
user: getUserInfo(),
});
} catch ({ message }) {
alert(message);
}
};
get collection() {
return firebase.firestore().collection(collectionName);
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;