/
firebase.js
82 lines (68 loc) · 2.26 KB
/
firebase.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
import { initializeApp } from 'firebase/app';
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
updateProfile,
} from 'firebase/auth';
import { getFirestore, collection, doc, setDoc } from 'firebase/firestore';
import { getDownloadURL, getStorage, ref, uploadBytes } from 'firebase/storage';
import config from '../firebase.json';
export const app = initializeApp(config);
const auth = getAuth(app);
export const signin = async ({ email, password }) => {
const { user } = await signInWithEmailAndPassword(auth, email, password);
return user;
};
const uploadImage = async uri => {
if (uri.startsWith('https')) {
return uri;
}
const response = await fetch(uri);
const blob = await response.blob();
const { uid } = auth.currentUser;
const storage = getStorage(app);
const storageRef = ref(storage, `/profile/${uid}/photo.png`);
await uploadBytes(storageRef, blob, {
contentType: 'image/png',
});
return await getDownloadURL(storageRef);
};
export const signup = async ({ name, email, password, photo }) => {
const { user } = await createUserWithEmailAndPassword(auth, email, password);
const photoURL = await uploadImage(photo);
await updateProfile(auth.currentUser, { displayName: name, photoURL });
return user;
};
export const getCurrentUser = () => {
const { uid, displayName, email, photoURL } = auth.currentUser;
return { uid, name: displayName, email, photo: photoURL };
};
export const updateUserInfo = async photo => {
const photoURL = await uploadImage(photo);
await updateProfile(auth.currentUser, { photoURL });
return photoURL;
};
export const signout = async () => {
await signOut(auth);
return {};
};
const db = getFirestore(app);
export const createChannel = async ({ title, desc }) => {
const channelCollection = collection(db, 'channels');
const newChannelRef = doc(channelCollection);
const id = newChannelRef.id;
const newChannel = {
id,
title,
description: desc,
createdAt: Date.now(),
};
await setDoc(newChannelRef, newChannel);
return id;
};
export const createMessage = async ({ channelId, message }) => {
const docRef = doc(db, `channels/${channelId}/messages`, message._id);
await setDoc(docRef, { ...message, createdAt: Date.now() });
};