-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.config.ts
110 lines (95 loc) · 2.32 KB
/
firebase.config.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
import { initializeApp } from 'firebase/app';
import {
Timestamp,
addDoc,
collection,
doc,
getDocs,
getFirestore,
setDoc,
updateDoc,
} from 'firebase/firestore';
import {
getAuth,
onAuthStateChanged,
GoogleAuthProvider,
signInWithPopup,
} from 'firebase/auth';
const firebaseConfig = {
apiKey: import.meta.env.VITE_API_KEY,
authDomain: import.meta.env.VITE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_PROJECT_ID,
storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_APP_ID,
measurementId: import.meta.env.VITE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
export const signIn = async () => {
await signInWithPopup(auth, provider);
};
export const signOut = () => {
auth.signOut();
};
export const getUsers = async () => {
const querySnapShot = await getDocs(collection(db, 'users'));
if (querySnapShot) {
return querySnapShot;
} else {
return null;
}
};
export const createRoom = async (roomName: string) => {
const docRef = await doc(db, 'rooms', roomName);
updateDoc(docRef, {})
.then(() => window.alert('Chat room exists'))
.catch(() => {
setDoc(docRef, {
name: roomName,
createdAt: Timestamp.now(),
});
window.alert('Created');
});
};
export const getRooms = async () => {
const querySnapShot = await getDocs(collection(db, 'rooms'));
if (querySnapShot) {
return querySnapShot;
} else {
return null;
}
};
export const getMessages = async (roomName: string) => {
const querySnapShot = await getDocs(
collection(db, 'rooms', roomName, 'messages')
);
if (querySnapShot) {
return querySnapShot;
} else {
return null;
}
};
export const createMessage = async (roomName: string, message: string) => {
await addDoc(collection(db, 'rooms', roomName, 'messages'), {
message: message,
user: auth.currentUser?.displayName,
createdAt: Timestamp.now(),
});
};
onAuthStateChanged(auth, async (result) => {
//CreateUserProfile
if (result) {
const docRef = doc(db, 'users', result.displayName || '');
updateDoc(docRef, {}).catch(() => {
setDoc(docRef, {
name: result.displayName,
email: result.email,
createdAt: Timestamp.now(),
});
});
}
});
export { db, auth };