fix(reviews): create serverless backend API to persist all reviews in list without overwriting
This commit is contained in:
1 parent
5f72536552
commit
699e4d8ff9
2 files changed
+214
-68
No files matched your search
+183
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* 🌟 Sovereign AIRA Verified Reviews Gateway (Vercel Serverless - ES Module)
|
||||
* Engineered for Aira Group of Technology (airaaigroup.in)
|
||||
* Founder & CEO: Er. Adam Eehan
|
||||
*
|
||||
* Features:
|
||||
* - Real-time persistent feedback list storage via secure backend proxy
|
||||
* - Eliminates client-side race conditions, CORS blocks, and overwrites
|
||||
* - Multi-user chronological review preservation (new reviews unshift, existing updates)
|
||||
* - Automated notification dispatch to Er. Adam Eehan
|
||||
*/
|
||||
|
||||
const JSONBIN_BIN_ID = process.env.JSONBIN_BIN_ID || "6ae98e5dffd5d16053a19fc4";
|
||||
const JSONBIN_API_KEY = process.env.JSONBIN_API_KEY || "$2a$10$0IoWYIJUtPPsZ9Y9fED.megYee63XlKIFxzn.cGXYPVu.TMqC.SKi";
|
||||
const BOSS_EMAIL = "adameehan34@gmail.com";
|
||||
|
||||
// Helper: Fetch latest reviews directly from JSONBin with zero caching
|
||||
async function fetchLatestFromBin() {
|
||||
try {
|
||||
const res = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_BIN_ID}/latest`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"X-Master-Key": JSONBIN_API_KEY,
|
||||
"X-Bin-Meta": "false",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate"
|
||||
}
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.error(`[Reviews API] JSONBin fetch failed with status ${res.status}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data && Array.isArray(data.feedbacks)) {
|
||||
return data.feedbacks;
|
||||
}
|
||||
return [];
|
||||
} catch (err) {
|
||||
console.error("[Reviews API] JSONBin fetch exception:", err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: Save entire reviews array back to JSONBin atomically
|
||||
async function saveToBin(feedbacks) {
|
||||
const res = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_BIN_ID}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Master-Key": JSONBIN_API_KEY,
|
||||
"X-Bin-Versioning": "false"
|
||||
},
|
||||
body: JSON.stringify({ feedbacks })
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`JSONBin PUT failed with code ${res.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export default async function handler(req, res) {
|
||||
// CORS & No-Cache Headers
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
return res.status(200).end();
|
||||
}
|
||||
|
||||
// --- GET: Fetch all reviews as list ---
|
||||
if (req.method === "GET") {
|
||||
try {
|
||||
const feedbacks = await fetchLatestFromBin();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
count: feedbacks.length,
|
||||
reviews: feedbacks
|
||||
});
|
||||
} catch (err) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: "Failed to load reviews.",
|
||||
message: err.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- POST: Add new review or update existing review without deleting others ---
|
||||
if (req.method === "POST") {
|
||||
try {
|
||||
const { name, email, photo, rating, tag, text, id, date } = req.body || {};
|
||||
|
||||
if (!text || !text.trim()) {
|
||||
return res.status(400).json({ success: false, error: "Review text is required." });
|
||||
}
|
||||
|
||||
const cleanName = (name && name.trim()) ? name.trim() : "Verified Member";
|
||||
const cleanEmail = (email && email.trim()) ? email.trim().toLowerCase() : "";
|
||||
const cleanText = text.trim().slice(0, 1500);
|
||||
const cleanRating = (typeof rating === "number" && rating >= 1 && rating <= 5) ? rating : 5;
|
||||
const cleanTag = (tag && tag.trim()) ? tag.trim() : "Client / Collaborator";
|
||||
const cleanPhoto = (photo && photo.trim()) ? photo.trim() : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(cleanName)}`;
|
||||
const cleanDate = date || new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
|
||||
const reviewId = id || ("rev_" + Date.now());
|
||||
|
||||
const newReview = {
|
||||
id: reviewId,
|
||||
name: cleanName,
|
||||
email: cleanEmail,
|
||||
photo: cleanPhoto,
|
||||
rating: cleanRating,
|
||||
tag: cleanTag,
|
||||
text: cleanText,
|
||||
date: cleanDate
|
||||
};
|
||||
|
||||
// 1. Fetch current list of reviews from cloud
|
||||
const currentFeedbacks = await fetchLatestFromBin();
|
||||
|
||||
// 2. Check if this user (by email) already submitted a review
|
||||
let updatedFeedbacks = [...currentFeedbacks];
|
||||
let existingIndex = -1;
|
||||
|
||||
if (cleanEmail) {
|
||||
existingIndex = updatedFeedbacks.findIndex(r => r.email && r.email.toLowerCase() === cleanEmail);
|
||||
}
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
// User is updating their existing review -> Move updated review to top
|
||||
updatedFeedbacks.splice(existingIndex, 1);
|
||||
updatedFeedbacks.unshift(newReview);
|
||||
} else {
|
||||
// New user -> Prepend to the list so older reviews are preserved!
|
||||
updatedFeedbacks.unshift(newReview);
|
||||
}
|
||||
|
||||
// 3. Atomically write back to cloud
|
||||
await saveToBin(updatedFeedbacks);
|
||||
|
||||
// 4. Background notification dispatch to Er. Adam Eehan
|
||||
try {
|
||||
fetch("https://formsubmit.co/ajax/" + BOSS_EMAIL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "Accept": "application/json" },
|
||||
body: JSON.stringify({
|
||||
_subject: `🌟 New Real Feedback: ${cleanName} (${cleanRating} Stars) - airaaigroup.in`,
|
||||
Name: cleanName,
|
||||
Email: cleanEmail,
|
||||
Rating: `${cleanRating} / 5 Stars`,
|
||||
Category: cleanTag,
|
||||
Review: cleanText,
|
||||
Date: cleanDate,
|
||||
TotalReviewsInDatabase: updatedFeedbacks.length
|
||||
})
|
||||
}).catch(() => {});
|
||||
} catch (mailErr) {
|
||||
// ignore background mail errors
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: "Review successfully published and preserved in cloud database.",
|
||||
count: updatedFeedbacks.length,
|
||||
reviews: updatedFeedbacks
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reviews API] Submit error:", err);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: "Failed to publish review.",
|
||||
message: err.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(405).json({ error: "Method not allowed. Use GET or POST." });
|
||||
}
|
||||
+31
-68
@@ -2896,12 +2896,8 @@
|
||||
// Sovereign Google OAuth & JSONBin.io Database Integration
|
||||
const GOOGLE_CLIENT_ID = "267802159841-leun1b8b85ongsoc5pkjhufe4s5jbjj8.apps.googleusercontent.com";
|
||||
|
||||
// JSONBin Database Config (Boss will provide Bin ID & Access Key)
|
||||
const JSONBIN_CONFIG = {
|
||||
binId: "6ae98e5dffd5d16053a19fc4",
|
||||
apiKey: "$2a$10$0IoWYIJUtPPsZ9Y9fED.megYee63XlKIFxzn.cGXYPVu.TMqC.SKi",
|
||||
accessKey: "$2a$10$jf/M7s48/qgR31ZlqFqg8.vGifgPuuFNzEfGzl2NTGjXo7pv2RHEC"
|
||||
};
|
||||
// Sovereign Reviews Backend API Gateway (Vercel Serverless Function)
|
||||
const REVIEWS_API_URL = "/api/reviews";
|
||||
|
||||
let currentUser = null;
|
||||
let currentRating = 5;
|
||||
@@ -3158,34 +3154,30 @@
|
||||
btn.className = "tag-opt active px-3 py-1.5 rounded-lg text-xs font-semibold bg-blue-600 text-white transition";
|
||||
}
|
||||
|
||||
// Fetch Reviews: JSONBin.io with LocalStorage fallback (Zero Fake Reviews)
|
||||
// Fetch Reviews: Serverless Backend API with LocalStorage fallback (Zero Fake Reviews)
|
||||
async function loadReviews() {
|
||||
const container = document.getElementById("verified-reviews-grid");
|
||||
if (!container) return;
|
||||
|
||||
// 1. Try to load from JSONBin if binId is configured
|
||||
if (JSONBIN_CONFIG.binId && JSONBIN_CONFIG.binId.length > 5) {
|
||||
try {
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (JSONBIN_CONFIG.apiKey) {
|
||||
headers["X-Master-Key"] = JSONBIN_CONFIG.apiKey;
|
||||
}
|
||||
const res = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_CONFIG.binId}/latest`, { headers });
|
||||
const res = await fetch(REVIEWS_API_URL, {
|
||||
method: "GET",
|
||||
headers: { "Cache-Control": "no-cache, no-store, must-revalidate" }
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data && data.record && Array.isArray(data.record.feedbacks)) {
|
||||
liveReviews = data.record.feedbacks;
|
||||
if (data && data.success && Array.isArray(data.reviews)) {
|
||||
liveReviews = data.reviews;
|
||||
localStorage.setItem("aira_verified_reviews", JSON.stringify(liveReviews));
|
||||
renderReviewsList();
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch(err) {
|
||||
console.log("JSONBin fetch fallback to local:", err);
|
||||
}
|
||||
console.warn("[Reviews] Server fetch fallback to local:", err);
|
||||
}
|
||||
|
||||
// 2. Fallback to LocalStorage
|
||||
// Fallback to LocalStorage if offline or network error
|
||||
const local = localStorage.getItem("aira_verified_reviews");
|
||||
if (local) {
|
||||
try {
|
||||
@@ -3200,7 +3192,7 @@
|
||||
renderReviewsList();
|
||||
}
|
||||
|
||||
// Submit Verified Review
|
||||
// Submit Verified Review via Sovereign API Gateway
|
||||
async function handleFeedbackSubmit(e) {
|
||||
e.preventDefault();
|
||||
if (!currentUser) {
|
||||
@@ -3215,7 +3207,7 @@
|
||||
const submitBtn = document.getElementById("submit-feedback-btn");
|
||||
const originalBtnHtml = submitBtn.innerHTML;
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin text-xs"></i> Posting...`;
|
||||
submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin text-xs"></i> Publishing...`;
|
||||
|
||||
const newReview = {
|
||||
id: "rev_" + Date.now(),
|
||||
@@ -3228,65 +3220,36 @@
|
||||
date: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
|
||||
};
|
||||
|
||||
// 1. Save to JSONBin with latest sync
|
||||
const authKey = JSONBIN_CONFIG.apiKey || JSONBIN_CONFIG.accessKey;
|
||||
if (JSONBIN_CONFIG.binId && authKey) {
|
||||
try {
|
||||
let latestFeedbacks = [];
|
||||
try {
|
||||
const fetchRes = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_CONFIG.binId}/latest`, {
|
||||
headers: { "X-Master-Key": authKey }
|
||||
const res = await fetch(REVIEWS_API_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(newReview)
|
||||
});
|
||||
if (fetchRes.ok) {
|
||||
const data = await fetchRes.json();
|
||||
if (data && data.record && Array.isArray(data.record.feedbacks)) {
|
||||
latestFeedbacks = data.record.feedbacks;
|
||||
}
|
||||
}
|
||||
} catch(fetchErr) {
|
||||
latestFeedbacks = [...liveReviews];
|
||||
}
|
||||
|
||||
latestFeedbacks.unshift(newReview);
|
||||
liveReviews = latestFeedbacks;
|
||||
|
||||
await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_CONFIG.binId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Master-Key": authKey
|
||||
},
|
||||
body: JSON.stringify({ feedbacks: liveReviews })
|
||||
});
|
||||
} catch(err) {
|
||||
console.error("JSONBin save error:", err);
|
||||
if (!liveReviews.find(r => r.id === newReview.id)) {
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data && data.success && Array.isArray(data.reviews)) {
|
||||
liveReviews = data.reviews;
|
||||
} else {
|
||||
// Optimistic update
|
||||
const existingIdx = liveReviews.findIndex(r => r.email && r.email.toLowerCase() === newReview.email.toLowerCase());
|
||||
if (existingIdx >= 0) liveReviews.splice(existingIdx, 1);
|
||||
liveReviews.unshift(newReview);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Reviews API returned status ${res.status}`);
|
||||
}
|
||||
} catch(err) {
|
||||
console.error("[Reviews] API error, saving optimistically to local cache:", err);
|
||||
const existingIdx = liveReviews.findIndex(r => r.email && r.email.toLowerCase() === newReview.email.toLowerCase());
|
||||
if (existingIdx >= 0) liveReviews.splice(existingIdx, 1);
|
||||
liveReviews.unshift(newReview);
|
||||
}
|
||||
|
||||
localStorage.setItem("aira_verified_reviews", JSON.stringify(liveReviews));
|
||||
renderReviewsList();
|
||||
|
||||
// 2. Email alert to Er. Adam Eehan via FormSubmit
|
||||
try {
|
||||
fetch("https://formsubmit.co/ajax/adameehan34@gmail.com", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "Accept": "application/json" },
|
||||
body: JSON.stringify({
|
||||
_subject: `🌟 New Real Feedback from ${currentUser.name} (${currentRating} Stars)`,
|
||||
Name: currentUser.name,
|
||||
Gmail: currentUser.email,
|
||||
Rating: `${currentRating} / 5 Stars`,
|
||||
Category: currentTag,
|
||||
Feedback: text
|
||||
})
|
||||
}).catch(() => {});
|
||||
} catch(err) {}
|
||||
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = originalBtnHtml;
|
||||
feedbackTextEl.value = "";
|
||||
|
||||
Reference in new issue
Block a user