Skip to content

Commit

Permalink
Merge pull request #152 from pbdsce/staging
Browse files Browse the repository at this point in the history
Merge staging to prod because Govind says so
  • Loading branch information
SkySingh04 authored Dec 27, 2024
2 parents 627f788 + 1b4f9f5 commit 5571dac
Show file tree
Hide file tree
Showing 6 changed files with 294 additions and 408 deletions.
355 changes: 174 additions & 181 deletions app/(default)/api/membersData/route.ts
Original file line number Diff line number Diff line change
@@ -1,209 +1,202 @@
import { NextResponse } from "next/server";
import { db, storage } from "@/Firebase";
import {
collection, addDoc, getDocs, DocumentData,
DocumentSnapshot,
doc,
updateDoc,
deleteDoc,
getDoc
} from 'firebase/firestore';
import { ref, uploadBytes, getDownloadURL, deleteObject } from 'firebase/storage';
collection,
addDoc,
getDocs,
DocumentData,
DocumentSnapshot,
doc,
updateDoc,
deleteDoc,
getDoc,
} from "firebase/firestore";
import {
ref,
uploadBytes,
getDownloadURL,
deleteObject,
} from "firebase/storage";

// GET handler to retrieve all members
export async function GET() {
try {
const querySnapshot = await getDocs(collection(db, "pbMembers"));

const membersRaw = querySnapshot.docs.map(
(doc: DocumentSnapshot<DocumentData>) => ({
id: doc.id,
...doc.data(),
})
);

const members = membersRaw.map((member: any) => ({
id: member.id,
name: member.name,
role: member.role,
company: member.company || '',
year: member.year,
linkedInUrl: member.linkedInUrl || '',
imageUrl: member.imageUrl || ''
}));

return NextResponse.json(members);
} catch (error:any) {
console.error("Error fetching members:", error);
return NextResponse.json(
{ error: "An error occurred while fetching members", details: error.message },
{ status: 500 }
);
try {
// Fetch all member documents from the Firestore collection
const querySnapshot = await getDocs(collection(db, "pbMembers"));

// Map the documents to extract data and include document ID
const membersRaw = querySnapshot.docs.map(
(doc: DocumentSnapshot<DocumentData>) => ({
id: doc.id,
...doc.data(),
})
);

// Format the members' data for the response
const members = membersRaw.map((member: any) => ({
id: member.id,
name: member.name,
role: member.role,
company: member.company || "",
year: member.year,
linkedInUrl: member.linkedInUrl || "",
imageUrl: member.imageUrl || "",
}));

// Return the formatted member data as JSON
return NextResponse.json(members);
} catch (error) {
// Catch any error during the fetching process
if (error instanceof Error) {
console.error("Error fetching members:", error.message);
return NextResponse.json(
{
error: "An error occurred while fetching members",
details: error.message,
},
{ status: 500 }
);
} else {
console.error("Unknown error:", error);
return NextResponse.json(
{ error: "An unknown error occurred while fetching members" },
{ status: 500 }
);
}
}
}

// test line
// POST handler to add a new member
export async function POST(request: Request) {
try {
const data = await request.json();
const { name, year, role, company, imageUrl, linkedInUrl } = data;

// Validation
if (!name) {
return NextResponse.json({ message: 'Missing Name.', error: true }, { status: 400 });
}
if (!year) {
return NextResponse.json({ message: 'Missing Year.', error: true }, { status: 400 });
}
if (!role) {
return NextResponse.json({ message: 'Missing Role.', error: true }, { status: 400 });
}

let downloadURL = '';
if (imageUrl) {
const response = await fetch(imageUrl);
if (!response.ok) {
return NextResponse.json({ message: 'Failed to fetch image from the URL.', error: true }, { status: 400 });
}

const contentType = response.headers.get('content-type');
if (!contentType || !contentType.startsWith('image/')) {
return NextResponse.json({ message: 'The provided URL is not a valid image.', error: true }, { status: 400 });
}

const blob = await response.blob();
const extension = contentType.split('/')[1];
const imageRef = ref(storage, `members/${name}.${extension}`);
await uploadBytes(imageRef, blob, { contentType });
downloadURL = await getDownloadURL(imageRef);
}

const docRef = await addDoc(collection(db, 'pbMembers'), {
name,
year,
role,
company,
linkedInUrl,
imageUrl: downloadURL,
});

return NextResponse.json({ message: 'Member added successfully', id: docRef.id }, { status: 201 });
} catch (error:any) {
console.error('Error adding member:', error);
return NextResponse.json({ message: `Failed to add member: ${error.message}`, error: true }, { status: 500 });
}
try {
// Parse the request body to extract member data
const data = await request.json();

const { name, year, role, company, imageUrl, linkedInUrl } = data;

export async function PUT(request: Request) {
try {
const data = await request.json();
const { id, name, year, role, company, imageUrl, linkedInUrl } = data;

// Validation
if (!id) {
return NextResponse.json({ message: 'Missing Member ID', error: true }, { status: 400 });
}
if (!name) {
return NextResponse.json({ message: 'Missing Name.', error: true }, { status: 400 });
}
if (!year) {
return NextResponse.json({ message: 'Missing Year.', error: true }, { status: 400 });
}
if (!role) {
return NextResponse.json({ message: 'Missing Role.', error: true }, { status: 400 });
}

const memberRef = doc(db, "pbMembers", id);
const memberSnapshot = await getDoc(memberRef);
if (!memberSnapshot.exists()) {
return NextResponse.json({ message: 'Member not found', error: true }, { status: 404 });
}

const memberData = memberSnapshot.data();
let downloadURL = memberData.imageUrl;

if (imageUrl && imageUrl !== memberData.imageUrl) {
const response = await fetch(imageUrl);
if (!response.ok) {
return NextResponse.json({ message: 'Failed to fetch image from the URL.', error: true }, { status: 400 });
}

const contentType = response.headers.get('content-type');
if (!contentType || !contentType.startsWith('image/')) {
return NextResponse.json({ message: 'The provided URL is not a valid image.', error: true }, { status: 400 });
}

const blob = await response.blob();
const extension = contentType.split('/')[1];
const timestamp = Date.now();
const imageRef = ref(storage, `members/${name}_${timestamp}.${extension}`);
await uploadBytes(imageRef, blob, { contentType });
downloadURL = await getDownloadURL(imageRef);

if (memberData.imageUrl) {
const oldImageRef = ref(storage, memberData.imageUrl);
await deleteObject(oldImageRef).catch(error => {
console.error('Error deleting old image:', error);
});
}
}

const updatedData = {
name,
year,
role,
company,
linkedInUrl,
imageUrl: downloadURL,
};

await updateDoc(memberRef, updatedData);

return NextResponse.json({ message: 'Member updated successfully', data: updatedData }, { status: 200 });
} catch (error:any) {
console.error('Error updating member:', error);
return NextResponse.json({ message: `Failed to update member: ${error.message}`, error: true }, { status: 500 });
// Check for missing required fields
if (!name) {
return NextResponse.json(
{ message: "Missing Name.", error: true },
{ status: 400 }
);
}

export async function DELETE(request: Request) {
try {
const { id } = await request.json();
// Add the new member document to the Firestore collection
const docRef = await addDoc(collection(db, "pbMembers"), {
name,
year,
role,
company,
linkedInUrl,
imageUrl,
});

// Return success response with the new member's document ID
return NextResponse.json(
{ message: "Member added successfully", id: docRef.id },
{ status: 201 }
);
} catch (error) {
// Catch and log any errors during member creation
console.error("Error adding member:", error);
return NextResponse.json(
{ message: `Failed to add member: ${error}`, error: true },
{ status: 500 }
);
}
}

// PUT handler to update an existing member
export async function PUT(request: Request) {
try {
// Parse the request body to get the updated member data
const data = await request.json();
const { id, name, imageUrl } = data;

// Check for missing required fields
if (!id || !name) {
return NextResponse.json(
{ message: "Missing required fields or member ID", error: true },
{ status: 400 }
);
}

// Validation
if (!id) {
return NextResponse.json({ message: 'Missing member ID', error: true }, { status: 400 });
}
// Update member data in Firestore
const updatedData = { ...data, imageUrl: imageUrl };
await updateDoc(doc(db, "pbMembers", id), updatedData);

// Return success response with the updated member data
return NextResponse.json(
{ message: "Member updated successfully", data: updatedData },
{ status: 200 }
);
} catch (error) {
// Catch and log any errors during member update
console.error("Error updating member:", error);
return NextResponse.json(
{ message: `Failed to update member: ${error}`, error: true },
{ status: 500 }
);
}
}

const memberRef = doc(db, 'pbMembers', id);
const memberSnapshot = await getDoc(memberRef);
// DELETE handler to delete a member and their image
export async function DELETE(request: Request) {
try {
// Parse the request body to get the member ID
const { id } = await request.json();

if (!memberSnapshot.exists()) {
return NextResponse.json({ message: 'Member not found', error: true }, { status: 404 });
}
// Check if the member ID is provided
if (!id) {
return NextResponse.json(
{ message: "Missing member ID", error: true },
{ status: 400 }
);
}

// Fetch the member document from Firestore
const memberRef = doc(db, "pbMembers", id);
const memberSnapshot = await getDoc(memberRef);

if (!memberSnapshot.exists()) {
// If the member does not exist, return a 404 response
if (!memberSnapshot.exists()) {
return NextResponse.json(
{ message: "Member not found", error: true },
{ status: 404 }
);
}
if (imageUrl) {
const imageRef = ref(storage, imageUrl);
await deleteObject(imageRef).catch((error) => {
console.error('Error deleting image from Firebase Storage:', error);
return NextResponse.json({ message: 'Failed to delete image from storage', error: true }, { status: 500 });
});
}

await deleteDoc(memberRef);

return NextResponse.json({ message: 'Member and associated image deleted successfully' }, { status: 200 });
} catch (error:any) {
console.error('Error deleting member:', error);
return NextResponse.json({ message: `Failed to delete member: ${error.message}`, error: true }, { status: 500 });

// Extract member data and image URL
const memberData = memberSnapshot.data();
const imageUrl = memberData.imageUrl;

// If an image URL exists, delete the image from Firebase Storage
if (imageUrl) {
const imageRef = ref(storage, imageUrl);
await deleteObject(imageRef).catch((error) => {
console.error("Error deleting image from Firebase Storage:", error);
return NextResponse.json(
{ message: "Failed to delete image from storage", error: true },
{ status: 500 }
);
});
}

// Delete the member document from Firestore
await deleteDoc(memberRef);

// Return success response after deletion
return NextResponse.json(
{ message: "Member and associated image deleted successfully" },
{ status: 200 }
);
} catch (error) {
// Catch and log any errors during the deletion process
console.error("Error deleting member:", error);
return NextResponse.json(
{ message: "Failed to delete member", error },
{ status: 500 }
);
}
}
Loading

0 comments on commit 5571dac

Please sign in to comment.