|
| 1 | +import { firestore as db } from '../../../../utils/firebaseInit'; |
| 2 | +import { collection, getDocs, addDoc, updateDoc, deleteDoc, doc , increment } from 'firebase/firestore'; |
| 3 | +import type { NextApiRequest, NextApiResponse } from 'next'; |
| 4 | + |
| 5 | +const COLLECTION_NAME = 'profReviews'; |
| 6 | + |
| 7 | +const handler = async (req: NextApiRequest, res: NextApiResponse) => { |
| 8 | + switch (req.method) { |
| 9 | + case 'GET': |
| 10 | + try { |
| 11 | + console.log("Fetching all reviews..."); |
| 12 | + const reviewsRef = collection(db, COLLECTION_NAME); |
| 13 | + const snapshot = await getDocs(reviewsRef); |
| 14 | + const reviews = snapshot.docs.map(doc => ({ |
| 15 | + id: doc.id, |
| 16 | + ...doc.data() |
| 17 | + })); |
| 18 | + res.status(200).json({ reviews }); |
| 19 | + } catch (error) { |
| 20 | + console.error('Error fetching reviews:', error); |
| 21 | + res.status(500).json({ error: 'Failed to fetch reviews' }); |
| 22 | + } |
| 23 | + break; |
| 24 | + |
| 25 | + case 'POST': |
| 26 | + try { |
| 27 | + const body = req.body; |
| 28 | + const reviewsRef = collection(db, COLLECTION_NAME); |
| 29 | + const docRef = await addDoc(reviewsRef, { |
| 30 | + ...body, |
| 31 | + date: new Date().toISOString().split('T')[0], |
| 32 | + upvotes: 0, |
| 33 | + comments: [] |
| 34 | + }); |
| 35 | + res.status(200).json({ id: docRef.id, ...body }); |
| 36 | + } catch (error) { |
| 37 | + console.error('Error adding review:', error); |
| 38 | + res.status(500).json({ error: 'Failed to add review' }); |
| 39 | + } |
| 40 | + break; |
| 41 | + |
| 42 | + case 'PUT': |
| 43 | + try { |
| 44 | + const body = req.body; |
| 45 | + const { id, ...updateData } = body; |
| 46 | + const reviewRef = doc(db, COLLECTION_NAME, id); |
| 47 | + |
| 48 | + await updateDoc(reviewRef, { |
| 49 | + upvotes: increment(1), |
| 50 | + ...updateData |
| 51 | + }); |
| 52 | + |
| 53 | + res.status(200).json({ success: true }); |
| 54 | + } catch (error) { |
| 55 | + console.error('Error updating review:', error); |
| 56 | + res.status(500).json({ error: 'Failed to update review' }); |
| 57 | + } |
| 58 | + break; |
| 59 | + |
| 60 | + |
| 61 | + case 'DELETE': |
| 62 | + try { |
| 63 | + const { id } = req.body; |
| 64 | + const reviewRef = doc(db, COLLECTION_NAME, id); |
| 65 | + await deleteDoc(reviewRef); |
| 66 | + res.status(200).json({ success: true }); |
| 67 | + } catch (error) { |
| 68 | + console.error('Error deleting review:', error); |
| 69 | + res.status(500).json({ error: 'Failed to delete review' }); |
| 70 | + } |
| 71 | + break; |
| 72 | + |
| 73 | + default: |
| 74 | + res.status(405).json({ error: 'Method Not Allowed' }); |
| 75 | + } |
| 76 | +}; |
| 77 | + |
| 78 | +export default handler; |
0 commit comments