fix(blog): resolve 404 and 500 error on blog post slug navigation
Deploy Canina / deploy (push) Has been cancelled
Deploy Canina / deploy (push) Has been cancelled
This commit is contained in:
1 parent
1ddfb0a823
commit
088f8e20bb
19 files changed
+145201
-5346
No files matched your search
@@ -10,16 +10,37 @@ import {
|
||||
Sparkles,
|
||||
ShoppingBag,
|
||||
ArrowLeft,
|
||||
Heart,
|
||||
Send,
|
||||
Eye,
|
||||
} from "lucide-react";
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { Metadata } from 'next';
|
||||
import SafeImage from "../../../components/SafeImage";
|
||||
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
||||
|
||||
function safeIso(val: any, fallback?: string): string | undefined {
|
||||
if (!val) return fallback;
|
||||
try {
|
||||
const d = new Date(val);
|
||||
return isNaN(d.getTime()) ? fallback : d.toISOString();
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function safeLocalDate(val: any): string {
|
||||
if (!val) return '';
|
||||
try {
|
||||
const d = new Date(val);
|
||||
return isNaN(d.getTime()) ? '' : d.toLocaleDateString('fa-IR');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function getBlog(rawSlug: string) {
|
||||
if (!rawSlug) return null;
|
||||
try {
|
||||
const slug = decodeURIComponent(rawSlug);
|
||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
@@ -31,7 +52,7 @@ async function getBlog(rawSlug: string) {
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error(`[Blog] Failed to fetch blog ${slug}: ${res.status}`);
|
||||
console.warn(`[Blog] Failed to fetch blog ${slug}: ${res.status}`);
|
||||
return null;
|
||||
}
|
||||
const b = await res.json();
|
||||
@@ -58,7 +79,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
const rawSiteUrl = process.env.NEXT_PUBLIC_SITE_URL || config.canonicalBaseUrl || 'https://canina.ir';
|
||||
const siteUrl = rawSiteUrl.replace(/\/+$/, '');
|
||||
|
||||
const metaTitle = blog.metaTitle || blog.title;
|
||||
const metaTitle = blog.metaTitle || blog.title || 'مقاله آموزشی و تخصصی کنینا';
|
||||
const title = formatPageTitle(metaTitle, config.brandNameFa, config.titleSeparator, config.titlePosition, false);
|
||||
const description =
|
||||
blog.metaDescription ||
|
||||
@@ -74,8 +95,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا'
|
||||
: 'نویسنده و پژوهشگر کنینا';
|
||||
|
||||
const publishedTime = blog.publishedAt ? new Date(blog.publishedAt).toISOString() : blog.createdAt ? new Date(blog.createdAt).toISOString() : undefined;
|
||||
const modifiedTime = blog.updatedAt ? new Date(blog.updatedAt).toISOString() : publishedTime;
|
||||
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
|
||||
const modifiedTime = safeIso(blog.updatedAt) || publishedTime;
|
||||
|
||||
const keywordsList = blog.focusKeywords
|
||||
? blog.focusKeywords.split(',').map((k: string) => k.trim())
|
||||
@@ -109,7 +130,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
url: ogImageUrl,
|
||||
width: 1200,
|
||||
height: 630,
|
||||
alt: blog.imageAlt || blog.title,
|
||||
alt: blog.imageAlt || blog.title || title,
|
||||
},
|
||||
],
|
||||
url: canonicalUrl,
|
||||
@@ -118,7 +139,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
publishedTime,
|
||||
modifiedTime,
|
||||
authors: [authorName],
|
||||
tags: blog.tags?.map((t: any) => t.name) || [],
|
||||
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
@@ -135,46 +156,23 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
const config = await getSeoConfig();
|
||||
|
||||
if (!blog) {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex flex-col items-center justify-center font-vazir text-center px-4" dir="rtl">
|
||||
<div className="w-16 h-16 rounded-3xl bg-red-100 text-red-600 flex items-center justify-center mb-4">
|
||||
<MessageSquare className="w-8 h-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl sm:text-3xl font-black text-medical-gray-900 mb-2">مقاله مورد نظر یافت نشد</h1>
|
||||
<p className="text-sm text-medical-gray-500 mb-6">احتمالاً این مقاله حذف یا به آدرس دیگری منتقل شده است.</p>
|
||||
<Link
|
||||
href="/blog"
|
||||
className="px-6 py-3 rounded-2xl bg-canina-blue text-white text-xs font-black flex items-center gap-2 hover:bg-canina-blue/90 shadow-md"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<span>بازگشت به مجله سلامت</span>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
notFound();
|
||||
}
|
||||
|
||||
const rawSiteUrl = process.env.NEXT_PUBLIC_SITE_URL || config.canonicalBaseUrl || 'https://canina.ir';
|
||||
const rawSiteUrl = process.env.NEXT_PUBLIC_SITE_URL || config.canonicalBaseUrl || 'https://canina.ir';
|
||||
const siteUrl = rawSiteUrl.replace(/\/+$/, '');
|
||||
|
||||
const authorName = blog.author
|
||||
? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا'
|
||||
: 'نویسنده و پژوهشگر کنینا';
|
||||
const publishedDate = blog.publishedAt
|
||||
? new Date(blog.publishedAt).toLocaleDateString('fa-IR')
|
||||
: blog.createdAt
|
||||
? new Date(blog.createdAt).toLocaleDateString('fa-IR')
|
||||
: '';
|
||||
const publishedDate = safeLocalDate(blog.publishedAt) || safeLocalDate(blog.createdAt);
|
||||
|
||||
const canonicalUrl = blog.canonicalUrl
|
||||
? blog.canonicalUrl.replace(/\/+$/, '')
|
||||
: `${siteUrl}/blog/${slug}`;
|
||||
|
||||
const publishedIso = blog.publishedAt
|
||||
? new Date(blog.publishedAt).toISOString()
|
||||
: blog.createdAt
|
||||
? new Date(blog.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
const modifiedIso = blog.updatedAt ? new Date(blog.updatedAt).toISOString() : publishedIso;
|
||||
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
|
||||
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
|
||||
|
||||
// JSON-LD Structured Data Schema (BlogPosting & BreadcrumbList)
|
||||
const schemaType = blog.schemaType || 'BlogPosting';
|
||||
@@ -216,7 +214,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
},
|
||||
},
|
||||
articleSection: blog.category?.name || 'دانشنامه سلامت حیوانات',
|
||||
keywords: blog.focusKeywords || blog.tags?.map((t: any) => t.name).join(', ') || undefined,
|
||||
keywords: blog.focusKeywords || (Array.isArray(blog.tags) ? blog.tags.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean).join(', ') : undefined),
|
||||
};
|
||||
|
||||
const breadcrumbJsonLd = {
|
||||
@@ -261,9 +259,9 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
],
|
||||
};
|
||||
|
||||
const relatedProducts = blog.relatedProducts || [];
|
||||
const relatedBlogs = blog.relatedBlogs || [];
|
||||
const comments = blog.comments || [];
|
||||
const relatedProducts = Array.isArray(blog.relatedProducts) ? blog.relatedProducts : [];
|
||||
const relatedBlogs = Array.isArray(blog.relatedBlogs) ? blog.relatedBlogs : [];
|
||||
const comments = Array.isArray(blog.comments) ? blog.comments : [];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-medical-gray-50 pt-8 pb-24 px-4 font-vazir" dir="rtl">
|
||||
@@ -302,14 +300,13 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
{/* Featured Image */}
|
||||
{blog.imageUrl && (
|
||||
<div className="aspect-video w-full overflow-hidden rounded-[2rem] relative mb-8 shadow-sm">
|
||||
<Image
|
||||
<SafeImage
|
||||
src={blog.imageUrl}
|
||||
alt={blog.imageAlt || blog.title}
|
||||
fill
|
||||
priority
|
||||
sizes="(max-width: 1024px) 100vw, 800px"
|
||||
className="w-full h-full object-cover"
|
||||
unoptimized
|
||||
className="w-full h-full"
|
||||
imgClassName="w-full h-full object-cover"
|
||||
/>
|
||||
{blog.imageCaption && (
|
||||
<div className="absolute bottom-0 inset-x-0 bg-black/60 backdrop-blur-sm text-white text-xs font-medium py-2 px-4 text-center">
|
||||
@@ -326,10 +323,12 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
{blog.category.name}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3.5 h-3.5 text-canina-blue" />
|
||||
<span>{publishedDate}</span>
|
||||
</div>
|
||||
{publishedDate && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3.5 h-3.5 text-canina-blue" />
|
||||
<span>{publishedDate}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="w-3.5 h-3.5 text-canina-blue" />
|
||||
<span>{blog.readingTime || 4} دقیقه مطالعه</span>
|
||||
@@ -359,21 +358,26 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
/>
|
||||
|
||||
{/* Tags Chip Footer */}
|
||||
{blog.tags && blog.tags.length > 0 && (
|
||||
{Array.isArray(blog.tags) && blog.tags.length > 0 && (
|
||||
<div className="pt-8 mt-10 border-t border-medical-gray-100 flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs font-bold text-medical-gray-400 flex items-center gap-1">
|
||||
<Tag className="w-3.5 h-3.5" />
|
||||
برچسبهای مرتبط:
|
||||
</span>
|
||||
{blog.tags.map((tag: any) => (
|
||||
<Link
|
||||
key={tag.id}
|
||||
href={`/blog?tag=${encodeURIComponent(tag.name)}`}
|
||||
className="px-3 py-1 bg-purple-50 text-purple-700 hover:bg-purple-100 border border-purple-200 rounded-xl text-xs font-bold transition-colors"
|
||||
>
|
||||
#{tag.name}
|
||||
</Link>
|
||||
))}
|
||||
{blog.tags.map((tag: any, idx: number) => {
|
||||
const tagName = typeof tag === 'string' ? tag : tag?.name || '';
|
||||
const tagId = tag?.id || idx;
|
||||
if (!tagName) return null;
|
||||
return (
|
||||
<Link
|
||||
key={tagId}
|
||||
href={`/blog?tag=${encodeURIComponent(tagName)}`}
|
||||
className="px-3 py-1 bg-purple-50 text-purple-700 hover:bg-purple-100 border border-purple-200 rounded-xl text-xs font-bold transition-colors"
|
||||
>
|
||||
#{tagName}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -393,11 +397,13 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
if (navigator.share) {
|
||||
navigator.share({ title: blog.title, url: window.location.href });
|
||||
} else {
|
||||
navigator.clipboard.writeText(window.location.href);
|
||||
alert('لینک مقاله در کلیپبورد کپی شد');
|
||||
if (typeof window !== 'undefined') {
|
||||
if (navigator.share) {
|
||||
navigator.share({ title: blog.title, url: window.location.href });
|
||||
} else {
|
||||
navigator.clipboard.writeText(window.location.href);
|
||||
alert('لینک مقاله در کلیپبورد کپی شد');
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="p-3 bg-white rounded-2xl hover:bg-canina-blue hover:text-white transition-all text-medical-gray-600 border border-medical-gray-200 shadow-xs cursor-pointer flex items-center gap-1.5 text-xs font-bold"
|
||||
@@ -467,7 +473,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
<div className="flex items-center justify-between text-xs font-bold">
|
||||
<span className="text-medical-gray-900">{c.authorName}</span>
|
||||
<span className="text-medical-gray-400 text-[10px]">
|
||||
{c.createdAt ? new Date(c.createdAt).toLocaleDateString('fa-IR') : ''}
|
||||
{safeLocalDate(c.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-medical-gray-600 leading-relaxed">{c.content}</p>
|
||||
@@ -503,12 +509,11 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
className="bg-white/10 hover:bg-white/20 border border-white/20 p-3.5 rounded-2xl flex items-center gap-3 transition-all group"
|
||||
>
|
||||
<div className="w-14 h-14 bg-white rounded-xl p-1.5 shrink-0 overflow-hidden relative group-hover:scale-105 transition-transform">
|
||||
<Image
|
||||
src={p.images?.[0]?.url || p.imageUrl || '/assets/images/product-placeholder.png'}
|
||||
<SafeImage
|
||||
src={p.imageUrl || (Array.isArray(p.images) && p.images[0]) || '/assets/images/product-placeholder.png'}
|
||||
alt={p.nameFa}
|
||||
fill
|
||||
className="w-full h-full object-contain"
|
||||
unoptimized
|
||||
className="w-full h-full"
|
||||
imgClassName="w-full h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
@@ -536,16 +541,15 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
{relatedBlogs.map((item: any) => (
|
||||
<Link
|
||||
key={item.id}
|
||||
href={`/blog/${item.slug}`}
|
||||
href={`/blog/${encodeURIComponent(item.slug || item.id)}`}
|
||||
className="flex items-center gap-3 group"
|
||||
>
|
||||
<div className="w-16 h-14 rounded-2xl overflow-hidden shrink-0 relative bg-medical-gray-100">
|
||||
<Image
|
||||
<SafeImage
|
||||
src={item.imageUrl || '/assets/images/blog-placeholder.png'}
|
||||
alt={item.title}
|
||||
fill
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
unoptimized
|
||||
className="w-full h-full"
|
||||
imgClassName="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
@@ -585,4 +589,3 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ export default function BlogPage({
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
|
||||
onClick={() => router.push(`/blog/${featuredPost.slug}`)}
|
||||
onClick={() => router.push(`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`)}
|
||||
>
|
||||
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
|
||||
<SafeImage
|
||||
@@ -308,7 +308,7 @@ export default function BlogPage({
|
||||
viewport={{ once: true }}
|
||||
transition={{ delay: idx * 0.05 }}
|
||||
className="bg-white rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-lg group hover:shadow-2xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between"
|
||||
onClick={() => router.push(`/blog/${post.slug}`)}
|
||||
onClick={() => router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)}
|
||||
>
|
||||
<div>
|
||||
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
|
||||
|
||||
@@ -113,6 +113,8 @@ export default function BlogPreviewSection() {
|
||||
|
||||
const formattedDate = new Date(blog.createdAt).toLocaleDateString("fa-IR");
|
||||
|
||||
const blogHref = `/blog/${encodeURIComponent(blog.slug || blog.id)}`;
|
||||
|
||||
return (
|
||||
<motion.article
|
||||
key={blog.id || idx}
|
||||
@@ -122,7 +124,7 @@ export default function BlogPreviewSection() {
|
||||
transition={{ delay: idx * 0.1 }}
|
||||
className="bg-medical-gray-50/60 rounded-[2rem] border border-medical-gray-100 overflow-hidden hover:shadow-lg hover:-translate-y-1 transition-all flex flex-col group"
|
||||
>
|
||||
<Link href={`/blog/${blog.slug}`} className="block relative aspect-video w-full overflow-hidden bg-medical-gray-100">
|
||||
<Link href={blogHref} className="block relative aspect-video w-full overflow-hidden bg-medical-gray-100">
|
||||
<SafeImage
|
||||
src={image}
|
||||
alt={blog.title}
|
||||
@@ -149,7 +151,7 @@ export default function BlogPreviewSection() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Link href={`/blog/${blog.slug}`}>
|
||||
<Link href={blogHref}>
|
||||
<h3 className="text-lg font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors line-clamp-2 leading-snug">
|
||||
{blog.title}
|
||||
</h3>
|
||||
@@ -161,7 +163,7 @@ export default function BlogPreviewSection() {
|
||||
{authorName}
|
||||
</span>
|
||||
<Link
|
||||
href={`/blog/${blog.slug}`}
|
||||
href={blogHref}
|
||||
className="text-xs font-black text-canina-blue group-hover:underline flex items-center gap-1"
|
||||
>
|
||||
{getText("blog_preview_read_article", "خواندن مقاله")}
|
||||
|
||||
Reference in new issue
Block a user