Add fallback Supabase fetch in BlogPost
cgen-345dafe77cd8422bbb20e48d3572f1db
This commit is contained in:
parent
288e691605
commit
343cb39f73
1 changed files with 32 additions and 2 deletions
|
|
@ -22,8 +22,38 @@ export default function BlogPost() {
|
|||
(async () => {
|
||||
try {
|
||||
if (!slug) return;
|
||||
const res = await fetch(`/api/blog/${encodeURIComponent(slug)}`);
|
||||
const data = res.ok ? await res.json() : null;
|
||||
// Primary: try server API
|
||||
let res = await fetch(`/api/blog/${encodeURIComponent(slug)}`);
|
||||
let data: any = null;
|
||||
|
||||
try {
|
||||
// Attempt to parse JSON response from server route
|
||||
if (res.ok) data = await res.json();
|
||||
} catch (e) {
|
||||
// If server returned HTML (dev server) or invalid JSON, fall back to Supabase REST
|
||||
try {
|
||||
const sbUrl = import.meta.env.VITE_SUPABASE_URL;
|
||||
const sbKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
|
||||
if (sbUrl && sbKey) {
|
||||
const url = `${sbUrl.replace(/\/$/, "")}/rest/v1/blog_posts?slug=eq.${encodeURIComponent(
|
||||
String(slug),
|
||||
)}&select=id,slug,title,excerpt,author,date,read_time,category,image,body_html,published_at`;
|
||||
const sbRes = await fetch(url, {
|
||||
headers: {
|
||||
apikey: sbKey as string,
|
||||
Authorization: `Bearer ${sbKey}`,
|
||||
},
|
||||
});
|
||||
if (sbRes.ok) {
|
||||
const arr = await sbRes.json();
|
||||
data = Array.isArray(arr) && arr.length ? arr[0] : null;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Supabase fallback fetch failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!cancelled) setPost(data);
|
||||
} catch (e) {
|
||||
console.warn("Blog post fetch failed:", e);
|
||||
|
|
|
|||
Loading…
Reference in a new issue