MCPcopy Create free account
hub / github.com/firebase/codelab-friendlychat-web / saveImageMessage

Function saveImageMessage

appcheck/hosting/src/index.js:142–168  ·  view source on GitHub ↗
(file)

Source from the content-addressed store, hash-verified

140 // Saves a new message containing an image in Firebase.
141 // This first saves the image in Firebase storage.
142 async function saveImageMessage(file) {
143 try {
144 // 1 - We add a message with a loading icon that will get updated with the shared image.
145 const messageRef = await addDoc(collection(getFirestore(), 'messages'), {
146 name: getUserName(),
147 imageUrl: LOADING_IMAGE_URL,
148 profilePicUrl: getProfilePicUrl(),
149 timestamp: serverTimestamp()
150 });
151
152 // 2 - Upload the image to Cloud Storage.
153 const filePath = `${getAuth().currentUser.uid}/${messageRef.id}/${file.name}`;
154 const newImageRef = ref(getStorage(), filePath);
155 const fileSnapshot = await uploadBytesResumable(newImageRef, file);
156
157 // 3 - Generate a public URL for the file.
158 const publicImageUrl = await getDownloadURL(newImageRef);
159
160 // 4 - Update the chat message placeholder with the image’s URL.
161 await updateDoc(messageRef,{
162 imageUrl: publicImageUrl,
163 storageUri: fileSnapshot.metadata.fullPath
164 });
165 } catch (error) {
166 console.error('There was an error uploading a file to Cloud Storage:', error);
167 }
168 }
169
170 // Saves the messaging device token to Cloud Firestore.
171 async function saveMessagingDeviceToken() {

Callers 1

onMediaFileSelectedFunction · 0.70

Calls 2

getUserNameFunction · 0.70
getProfilePicUrlFunction · 0.70

Tested by

no test coverage detected