Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added image upload component and backend call #132

Merged
merged 3 commits into from
Sep 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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}` };
}
}