Skip to content

Commit

Permalink
Image Upload Backend Endpoint (#132)
Browse files Browse the repository at this point in the history
* Added image upload component and backend call

* Clean and combine code

---------

Co-authored-by: Parker Abramson <parkerrabramson@gmail.com>
  • Loading branch information
ahong75 and parkerra authored Sep 24, 2024
1 parent 74dd60e commit dfa1ca7
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions web/db/actions/caregiver/Photo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from "react";
import { db, storage } from "../../firebase"; // import firebase storage
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { doc, setDoc, Timestamp } from "firebase/firestore";

export async function uploadPhoto(e: React.ChangeEvent<HTMLInputElement>) {
const files = e.target.files;
if (!files || files.length === 0) {
return { success: false, error: "File attempted to be uploaded was empty" };
}

try {
const file = files[0];

const extension = file.name.split(".").pop();
const storageRef = ref(storage, `images/${Date.now()}.${extension}`);

const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},
(error) => {
return { success: false, error: `Upload failed: ${error}` };
},
async () => {
const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
// TODO: Incorporate baby and caregiver context
// https://github.com/GTBitsOfGood/motherhood-beyond-bars/blob/_original/mobile/screens/babybook/SelectPicture.tsx#L28
// TODO: Incorporate caption
const metadata = {
imageURL: downloadURL,
caregiverID: "test-caregiverId",
caption: "test-caption",
babyID: "test-babyId",
};

const { imageURL, caregiverID, caption, babyID } = metadata;

const docRef = doc(
db,
"babies",
babyID,
"book",
`${caregiverID}_${Date.now()}`
);

await setDoc(docRef, {
imageUrl: imageURL,
caption: caption,
date: Timestamp.now(),
caregiverId: caregiverID,
});

return { success: true, data: { downloadURL: downloadURL } };
}
);
} catch (error) {
return { success: false, error: `Upload failed: ${error}` };
}
}

0 comments on commit dfa1ca7

Please sign in to comment.