.
This commit is contained in:
9
LOG.md
9
LOG.md
@@ -2,6 +2,15 @@
|
|||||||
|
|
||||||
## 2026-05-29
|
## 2026-05-29
|
||||||
|
|
||||||
|
- Investigated Google Search Console crawlability concerns for the live site.
|
||||||
|
- Checked live `robots.txt`, `sitemap.xml`, homepage, sample post pages, and backend post API with a Googlebot user agent; public post URLs in the sitemap returned 200 with no `X-Robots-Tag` or meta robots block.
|
||||||
|
- Confirmed the non-www production host `blog.wypark.me` is the relevant host; its home/archive initial HTML currently contains no `/posts/` links because public lists are client-side rendered.
|
||||||
|
- Identified crawlability risk areas: home/archive rely on client-side post-list fetching, local builds generate a static-only sitemap when the backend API is unreachable, sitemap `lastmod` values can be timezone-skewed when backend timestamps omit an offset, and canonical URLs are not currently emitted.
|
||||||
|
- Validation: `npm run build` passed. As expected without a local backend, build-time sitemap generation logged `fetch failed` and produced only static sitemap entries in the local `.next` output.
|
||||||
|
- Converted home and archive pages to server-rendered public post lists through a dedicated `src/api/publicPosts.ts` fetch helper so first HTML now includes discoverable `/posts/` links.
|
||||||
|
- Added centralized site metadata utilities, canonical metadata for public pages/posts, dynamic sitemap generation, KST-aware API date parsing for `lastmod`, and robots/site URL reuse.
|
||||||
|
- Validation: `npm run lint` passed and `npm run build` passed. A local production server with `NEXT_PUBLIC_API_URL=https://blogserver.wypark.me` returned 22 `/posts/` links on `/`, 204 on `/archive`, canonical URLs for both pages, and sitemap output with 104 URLs including 102 post URLs.
|
||||||
|
- Recommended next task: deploy the SEO crawlability fix, then resubmit `https://blog.wypark.me/sitemap.xml` and a representative post URL in Google Search Console URL Inspection.
|
||||||
- Redesigned the app shell into a macOS-inspired blog OS with pastel desktop background tokens, translucent menu bar, quick-launch Dock, and reusable window surfaces.
|
- Redesigned the app shell into a macOS-inspired blog OS with pastel desktop background tokens, translucent menu bar, quick-launch Dock, and reusable window surfaces.
|
||||||
- Applied the window treatment to the home dashboard, post reader, archive, category view, auth screens, chess puzzle view, and admin management shells.
|
- Applied the window treatment to the home dashboard, post reader, archive, category view, auth screens, chess puzzle view, and admin management shells.
|
||||||
- Restored the missing local `chess.js` install in `node_modules` so build verification could run; no dependency version changes were intended.
|
- Restored the missing local `chess.js` install in `node_modules` so build verification could run; no dependency version changes were intended.
|
||||||
|
|||||||
68
src/api/publicPosts.ts
Normal file
68
src/api/publicPosts.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import { ApiResponse, Post, PostListResponse } from '@/types';
|
||||||
|
|
||||||
|
export const PUBLIC_POSTS_REVALIDATE_SECONDS = 300;
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
|
||||||
|
|
||||||
|
type PublicPostListParams = {
|
||||||
|
page?: number;
|
||||||
|
size?: number;
|
||||||
|
keyword?: string;
|
||||||
|
category?: string;
|
||||||
|
tag?: string;
|
||||||
|
sort?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildPostListUrl = (params: PublicPostListParams = {}) => {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
|
||||||
|
Object.entries({
|
||||||
|
...params,
|
||||||
|
sort: params.sort || 'createdAt,desc',
|
||||||
|
}).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== '') {
|
||||||
|
searchParams.set(key, String(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return `${API_URL}/api/posts?${searchParams.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fetchPublicPosts = async (
|
||||||
|
params: PublicPostListParams = {},
|
||||||
|
): Promise<PostListResponse | null> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(buildPostListUrl(params), {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
next: { revalidate: PUBLIC_POSTS_REVALIDATE_SECONDS },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
|
||||||
|
const json = (await response.json()) as ApiResponse<PostListResponse>;
|
||||||
|
return json.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Public posts fetch error:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fetchPublicPost = async (slug: string): Promise<Post | null> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/api/posts/${encodeURIComponent(slug)}`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
next: { revalidate: 60 },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
|
||||||
|
const json = (await response.json()) as ApiResponse<Post>;
|
||||||
|
return json.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Public post fetch error:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
@@ -1,61 +1,76 @@
|
|||||||
'use client';
|
import type { Metadata } from 'next';
|
||||||
|
|
||||||
import { useMemo } from 'react';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { format } from 'date-fns';
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { Archive, Calendar, ChevronRight, FileText, Loader2 } from 'lucide-react';
|
import { Archive, Calendar, ChevronRight, FileText } from 'lucide-react';
|
||||||
import { getPosts } from '@/api/posts';
|
import {
|
||||||
|
fetchPublicPosts,
|
||||||
|
} from '@/api/publicPosts';
|
||||||
import EmptyState from '@/components/ui/EmptyState';
|
import EmptyState from '@/components/ui/EmptyState';
|
||||||
import StatusBadge from '@/components/ui/StatusBadge';
|
import StatusBadge from '@/components/ui/StatusBadge';
|
||||||
import Surface from '@/components/ui/Surface';
|
import Surface from '@/components/ui/Surface';
|
||||||
import WindowSurface from '@/components/ui/WindowSurface';
|
import WindowSurface from '@/components/ui/WindowSurface';
|
||||||
|
import { SITE_NAME } from '@/lib/site';
|
||||||
import { Post, PostListResponse } from '@/types';
|
import { Post, PostListResponse } from '@/types';
|
||||||
|
|
||||||
const getTotalElements = (data?: PostListResponse) => {
|
export const dynamic = 'force-dynamic';
|
||||||
|
export const revalidate = 300;
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'Archive',
|
||||||
|
alternates: {
|
||||||
|
canonical: '/archive',
|
||||||
|
},
|
||||||
|
openGraph: {
|
||||||
|
title: `Archive | ${SITE_NAME}`,
|
||||||
|
url: '/archive',
|
||||||
|
siteName: SITE_NAME,
|
||||||
|
type: 'website',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTotalElements = (data?: PostListResponse | null) => {
|
||||||
return data?.page?.totalElements ?? data?.totalElements ?? 0;
|
return data?.page?.totalElements ?? data?.totalElements ?? 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function ArchivePage() {
|
const formatDate = (value: string) => {
|
||||||
const { data, isLoading } = useQuery({
|
const date = new Date(value);
|
||||||
queryKey: ['posts', 'all'],
|
if (Number.isNaN(date.getTime())) return '';
|
||||||
queryFn: () => getPosts({ page: 0, size: 1000 }),
|
|
||||||
staleTime: 1000 * 60 * 5,
|
|
||||||
});
|
|
||||||
|
|
||||||
const archiveGroups = useMemo(() => {
|
return new Intl.DateTimeFormat('ko-KR', {
|
||||||
if (!data?.content) return {};
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
}).format(date);
|
||||||
|
};
|
||||||
|
|
||||||
const groups: { [year: string]: { [month: string]: Post[] } } = {};
|
const groupPostsByMonth = (posts: Post[]) => {
|
||||||
|
const groups: Record<string, Record<string, Post[]>> = {};
|
||||||
|
|
||||||
data.content.forEach((post) => {
|
posts.forEach((post) => {
|
||||||
const date = new Date(post.createdAt);
|
const date = new Date(post.createdAt);
|
||||||
|
if (Number.isNaN(date.getTime())) return;
|
||||||
|
|
||||||
const year = date.getFullYear().toString();
|
const year = date.getFullYear().toString();
|
||||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
|
||||||
if (!groups[year]) groups[year] = {};
|
groups[year] ??= {};
|
||||||
if (!groups[year][month]) groups[year][month] = [];
|
groups[year][month] ??= [];
|
||||||
|
|
||||||
groups[year][month].push(post);
|
groups[year][month].push(post);
|
||||||
});
|
});
|
||||||
|
|
||||||
return groups;
|
return groups;
|
||||||
}, [data]);
|
};
|
||||||
|
|
||||||
const sortedYears = useMemo(() => {
|
const sortPostsNewestFirst = (posts: Post[]) => {
|
||||||
return Object.keys(archiveGroups).sort((a, b) => Number(b) - Number(a));
|
return [...posts].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||||
}, [archiveGroups]);
|
};
|
||||||
|
|
||||||
|
export default async function ArchivePage() {
|
||||||
|
const data = await fetchPublicPosts({ page: 0, size: 1000, sort: 'createdAt,desc' });
|
||||||
|
const posts = data?.content || [];
|
||||||
|
const archiveGroups = groupPostsByMonth(posts);
|
||||||
|
const sortedYears = Object.keys(archiveGroups).sort((a, b) => Number(b) - Number(a));
|
||||||
const totalPosts = getTotalElements(data);
|
const totalPosts = getTotalElements(data);
|
||||||
|
|
||||||
if (isLoading) {
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-[50vh] items-center justify-center">
|
|
||||||
<Loader2 className="animate-spin text-[var(--color-accent)]" size={40} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
||||||
<WindowSurface
|
<WindowSurface
|
||||||
@@ -92,15 +107,15 @@ export default function ArchivePage() {
|
|||||||
|
|
||||||
<div className="space-y-8 md:pl-12">
|
<div className="space-y-8 md:pl-12">
|
||||||
{sortedMonths.map((month) => {
|
{sortedMonths.map((month) => {
|
||||||
const posts = months[month];
|
const monthPosts = months[month];
|
||||||
const sortedPosts = [...posts].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
const sortedPosts = sortPostsNewestFirst(monthPosts);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={month} className="group">
|
<div key={month} className="group">
|
||||||
<h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-[var(--color-text-muted)]">
|
<h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-[var(--color-text-muted)]">
|
||||||
<Calendar size={18} className="text-[var(--color-text-subtle)]" />
|
<Calendar size={18} className="text-[var(--color-text-subtle)]" />
|
||||||
{month}월
|
{month}월
|
||||||
<StatusBadge tone="neutral">{posts.length}</StatusBadge>
|
<StatusBadge tone="neutral">{monthPosts.length}</StatusBadge>
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
@@ -117,9 +132,9 @@ export default function ArchivePage() {
|
|||||||
</h4>
|
</h4>
|
||||||
<div className="mt-1.5 flex items-center gap-2 text-xs text-[var(--color-text-subtle)]">
|
<div className="mt-1.5 flex items-center gap-2 text-xs text-[var(--color-text-subtle)]">
|
||||||
<StatusBadge tone="neutral" className="px-1.5 py-0.5">{post.categoryName || '미분류'}</StatusBadge>
|
<StatusBadge tone="neutral" className="px-1.5 py-0.5">{post.categoryName || '미분류'}</StatusBadge>
|
||||||
<span>·</span>
|
<span aria-hidden="true">·</span>
|
||||||
<span className="tabular-nums">
|
<span className="tabular-nums">
|
||||||
{format(new Date(post.createdAt), 'yyyy.MM.dd')}
|
{formatDate(post.createdAt)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -138,7 +153,7 @@ export default function ArchivePage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<EmptyState
|
<EmptyState
|
||||||
title="아직 작성된 기록이 없습니다."
|
title="아직 작성한 글이 없습니다."
|
||||||
icon={<FileText size={48} />}
|
icon={<FileText size={48} />}
|
||||||
className="py-20"
|
className="py-20"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import './globals.css';
|
|||||||
import Providers from './providers';
|
import Providers from './providers';
|
||||||
import DesktopShell from '@/components/layout/DesktopShell';
|
import DesktopShell from '@/components/layout/DesktopShell';
|
||||||
import { THEME_INIT_SCRIPT } from '@/components/theme/theme';
|
import { THEME_INIT_SCRIPT } from '@/components/theme/theme';
|
||||||
|
import { DEFAULT_DESCRIPTION, SITE_NAME, SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
const pretendard = localFont({
|
const pretendard = localFont({
|
||||||
src: './fonts/PretendardVariable.woff2',
|
src: './fonts/PretendardVariable.woff2',
|
||||||
@@ -14,8 +15,23 @@ const pretendard = localFont({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'WYPark Blog',
|
metadataBase: new URL(SITE_URL),
|
||||||
description: '개발 블로그',
|
title: {
|
||||||
|
default: SITE_NAME,
|
||||||
|
template: `%s | ${SITE_NAME}`,
|
||||||
|
},
|
||||||
|
description: DEFAULT_DESCRIPTION,
|
||||||
|
alternates: {
|
||||||
|
canonical: '/',
|
||||||
|
},
|
||||||
|
openGraph: {
|
||||||
|
title: SITE_NAME,
|
||||||
|
description: DEFAULT_DESCRIPTION,
|
||||||
|
url: '/',
|
||||||
|
siteName: SITE_NAME,
|
||||||
|
type: 'website',
|
||||||
|
locale: 'ko_KR',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
@@ -54,3 +70,4 @@ export default function RootLayout({
|
|||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
131
src/app/page.tsx
131
src/app/page.tsx
@@ -1,27 +1,52 @@
|
|||||||
'use client';
|
import type { Metadata } from 'next';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
import { Suspense, type ReactNode } from 'react';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { useSearchParams } from 'next/navigation';
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import {
|
import {
|
||||||
Archive,
|
Archive,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Clock,
|
Clock,
|
||||||
Loader2,
|
|
||||||
Search,
|
Search,
|
||||||
TrendingUp,
|
TrendingUp,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { getPosts } from '@/api/posts';
|
import {
|
||||||
|
fetchPublicPosts,
|
||||||
|
} from '@/api/publicPosts';
|
||||||
import EmptyState from '@/components/ui/EmptyState';
|
import EmptyState from '@/components/ui/EmptyState';
|
||||||
import StatusBadge from '@/components/ui/StatusBadge';
|
import StatusBadge from '@/components/ui/StatusBadge';
|
||||||
import Surface from '@/components/ui/Surface';
|
import Surface from '@/components/ui/Surface';
|
||||||
import WindowSurface from '@/components/ui/WindowSurface';
|
import WindowSurface from '@/components/ui/WindowSurface';
|
||||||
|
import { DEFAULT_DESCRIPTION, SITE_NAME } from '@/lib/site';
|
||||||
import { Post, PostListResponse } from '@/types';
|
import { Post, PostListResponse } from '@/types';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
export const revalidate = 300;
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: {
|
||||||
|
absolute: SITE_NAME,
|
||||||
|
},
|
||||||
|
description: DEFAULT_DESCRIPTION,
|
||||||
|
alternates: {
|
||||||
|
canonical: '/',
|
||||||
|
},
|
||||||
|
openGraph: {
|
||||||
|
title: SITE_NAME,
|
||||||
|
description: DEFAULT_DESCRIPTION,
|
||||||
|
url: '/',
|
||||||
|
siteName: SITE_NAME,
|
||||||
|
type: 'website',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
type HomePageProps = {
|
||||||
|
searchParams?: Promise<Record<string, string | string[] | undefined>>;
|
||||||
|
};
|
||||||
|
|
||||||
const isNoticePost = (post: Post) => {
|
const isNoticePost = (post: Post) => {
|
||||||
const categoryName = post.categoryName || '';
|
const categoryName = post.categoryName || '';
|
||||||
return categoryName === '공지' || categoryName === '怨듭?' || categoryName.toLowerCase() === 'notice';
|
const normalizedName = categoryName.toLowerCase();
|
||||||
|
|
||||||
|
return categoryName === '공지' || normalizedName === 'notice' || normalizedName === 'announcement';
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatDate = (value?: string) => {
|
const formatDate = (value?: string) => {
|
||||||
@@ -50,18 +75,23 @@ const getSummary = (content?: string, maxLength = 118) => {
|
|||||||
.slice(0, maxLength);
|
.slice(0, maxLength);
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTotalElements = (data?: PostListResponse) => {
|
const getTotalElements = (data?: PostListResponse | null) => {
|
||||||
return data?.page?.totalElements ?? data?.totalElements ?? 0;
|
return data?.page?.totalElements ?? data?.totalElements ?? 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getSearchKeyword = async (searchParams?: HomePageProps['searchParams']) => {
|
||||||
|
const resolvedSearchParams = searchParams ? await searchParams : {};
|
||||||
|
const keyword = resolvedSearchParams.keyword;
|
||||||
|
|
||||||
|
return Array.isArray(keyword) ? keyword[0] || '' : keyword || '';
|
||||||
|
};
|
||||||
|
|
||||||
function SearchResults({
|
function SearchResults({
|
||||||
keyword,
|
keyword,
|
||||||
data,
|
data,
|
||||||
isLoading,
|
|
||||||
}: {
|
}: {
|
||||||
keyword: string;
|
keyword: string;
|
||||||
data?: PostListResponse;
|
data?: PostListResponse | null;
|
||||||
isLoading: boolean;
|
|
||||||
}) {
|
}) {
|
||||||
const searchResults = data?.content || [];
|
const searchResults = data?.content || [];
|
||||||
const searchTotalElements = getTotalElements(data);
|
const searchTotalElements = getTotalElements(data);
|
||||||
@@ -85,11 +115,7 @@ function SearchResults({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
{searchResults.length > 0 ? (
|
||||||
<div className="flex min-h-60 items-center justify-center">
|
|
||||||
<Loader2 className="animate-spin text-[var(--color-accent)]" size={30} />
|
|
||||||
</div>
|
|
||||||
) : searchResults.length > 0 ? (
|
|
||||||
<div className="divide-y divide-[var(--color-line)]">
|
<div className="divide-y divide-[var(--color-line)]">
|
||||||
{searchResults.map((post) => (
|
{searchResults.map((post) => (
|
||||||
<CompactPostRow key={post.id} post={post} />
|
<CompactPostRow key={post.id} post={post} />
|
||||||
@@ -228,59 +254,32 @@ function PostListPanel({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function HomeContent() {
|
export default async function Home({ searchParams }: HomePageProps) {
|
||||||
const searchParams = useSearchParams();
|
const keyword = await getSearchKeyword(searchParams);
|
||||||
const keyword = searchParams.get('keyword') || '';
|
|
||||||
|
|
||||||
const { data: noticesData, isLoading: isNoticesLoading } = useQuery({
|
|
||||||
queryKey: ['posts', 'notices'],
|
|
||||||
queryFn: () => getPosts({ category: '공지', size: 3, sort: 'createdAt,desc' }),
|
|
||||||
retry: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: latestData, isLoading: isLatestLoading } = useQuery({
|
|
||||||
queryKey: ['posts', 'latest'],
|
|
||||||
queryFn: () => getPosts({ size: 8, sort: 'createdAt,desc' }),
|
|
||||||
retry: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: popularData, isLoading: isPopularLoading } = useQuery({
|
|
||||||
queryKey: ['posts', 'popular'],
|
|
||||||
queryFn: () => getPosts({ size: 8, sort: 'viewCount,desc' }),
|
|
||||||
retry: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: searchData, isLoading: isSearchLoading } = useQuery({
|
|
||||||
queryKey: ['posts', 'search', keyword],
|
|
||||||
queryFn: () => getPosts({ keyword, size: 20 }),
|
|
||||||
enabled: !!keyword,
|
|
||||||
retry: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const notices = noticesData?.content || [];
|
|
||||||
const latestList = (latestData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
|
|
||||||
const popularList = (popularData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
|
|
||||||
const isHomeLoading = !keyword && (isNoticesLoading || isLatestLoading || isPopularLoading);
|
|
||||||
|
|
||||||
if (keyword) {
|
if (keyword) {
|
||||||
|
const searchData = await fetchPublicPosts({ keyword, size: 20 });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
||||||
<SearchResults keyword={keyword} data={searchData} isLoading={isSearchLoading} />
|
<SearchResults keyword={keyword} data={searchData} />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isHomeLoading) {
|
const [noticesData, latestData, popularData] = await Promise.all([
|
||||||
return (
|
fetchPublicPosts({ category: '공지', size: 3, sort: 'createdAt,desc' }),
|
||||||
<div className="flex min-h-[60vh] items-center justify-center">
|
fetchPublicPosts({ size: 8, sort: 'createdAt,desc' }),
|
||||||
<Loader2 className="animate-spin text-[var(--color-accent)]" size={36} />
|
fetchPublicPosts({ size: 8, sort: 'viewCount,desc' }),
|
||||||
</div>
|
]);
|
||||||
);
|
|
||||||
}
|
const notices = noticesData?.content || [];
|
||||||
|
const latestList = (latestData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
|
||||||
|
const popularList = (popularData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
|
||||||
<h1 className="sr-only">WYPark Blog</h1>
|
<h1 className="sr-only">{SITE_NAME}</h1>
|
||||||
<WindowSurface
|
<WindowSurface
|
||||||
title="WYPark"
|
title="WYPark"
|
||||||
controls={(
|
controls={(
|
||||||
@@ -313,17 +312,3 @@ function HomeContent() {
|
|||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Home() {
|
|
||||||
return (
|
|
||||||
<Suspense
|
|
||||||
fallback={(
|
|
||||||
<div className="flex min-h-[60vh] items-center justify-center">
|
|
||||||
<Loader2 className="animate-spin text-[var(--color-accent)]" size={36} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<HomeContent />
|
|
||||||
</Suspense>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,87 +1,90 @@
|
|||||||
import { Metadata } from 'next';
|
import { Metadata } from 'next';
|
||||||
import PostDetailClient from '@/components/post/PostDetailClient';
|
|
||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
import { Post } from '@/types';
|
import { fetchPublicPost } from '@/api/publicPosts';
|
||||||
|
import PostDetailClient from '@/components/post/PostDetailClient';
|
||||||
|
import { DEFAULT_DESCRIPTION, getCanonicalUrl, parseApiDate, SITE_NAME, SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
params: Promise<{ slug: string }>;
|
params: Promise<{ slug: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
// 🛠️ 서버 사이드 데이터 패칭 함수 (Metadata와 Page 양쪽에서 재사용)
|
const getPostDescription = (content?: string) => {
|
||||||
async function getPostFromServer(slug: string): Promise<Post | null> {
|
const plainText = content
|
||||||
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
|
?.replace(/```[\s\S]*?```/g, ' ')
|
||||||
|
.replace(/!\[(.*?)\]\(.*?\)/g, '$1')
|
||||||
|
.replace(/\[(.*?)\]\(.*?\)/g, '$1')
|
||||||
|
.replace(/[#*`_~>]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
if (!plainText) return DEFAULT_DESCRIPTION;
|
||||||
|
|
||||||
|
return plainText.length > 150 ? `${plainText.slice(0, 150)}...` : plainText;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getFirstMarkdownImage = (content?: string) => {
|
||||||
|
const imageMatch = content?.match(/!\[.*?\]\((.*?)\)/);
|
||||||
|
const imageUrl = imageMatch?.[1]?.split(/\s+/)[0] || '/og-image.png';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${BASE_URL}/api/posts/${slug}`, {
|
return new URL(imageUrl, SITE_URL).toString();
|
||||||
// 캐시 설정: 60초마다 갱신 (블로그 특성상 적절)
|
} catch {
|
||||||
// 즉시 반영이 필요하다면 'no-store'로 설정하거나 revalidate: 0 사용
|
return new URL('/og-image.png', SITE_URL).toString();
|
||||||
next: { revalidate: 60 },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) return null;
|
|
||||||
|
|
||||||
const json = await res.json();
|
|
||||||
return json.data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Server fetch error:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// 🌟 메타데이터 생성 (SEO)
|
|
||||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
const { slug } = await params;
|
const { slug } = await params;
|
||||||
const post = await getPostFromServer(slug);
|
const post = await fetchPublicPost(slug);
|
||||||
|
const canonicalUrl = getCanonicalUrl(`/posts/${encodeURIComponent(post?.slug || slug)}`);
|
||||||
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
return {
|
return {
|
||||||
title: '게시글을 찾을 수 없습니다',
|
title: '게시글을 찾을 수 없습니다',
|
||||||
|
alternates: {
|
||||||
|
canonical: canonicalUrl,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 본문 요약 및 이미지 추출 로직
|
const description = getPostDescription(post.content);
|
||||||
const description = post.content
|
const imageUrl = getFirstMarkdownImage(post.content);
|
||||||
?.replace(/[#*`_~]/g, '')
|
const publishedTime = parseApiDate(post.createdAt).toISOString();
|
||||||
.replace(/\n/g, ' ')
|
const modifiedTime = parseApiDate(post.updatedAt || post.createdAt).toISOString();
|
||||||
.substring(0, 150) + '...';
|
|
||||||
|
|
||||||
const imageMatch = post.content?.match(/!\[.*?\]\((.*?)\)/);
|
|
||||||
const imageUrl = imageMatch ? imageMatch[1] : '/og-image.png';
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
description: description,
|
description,
|
||||||
|
alternates: {
|
||||||
|
canonical: canonicalUrl,
|
||||||
|
},
|
||||||
openGraph: {
|
openGraph: {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
description: description,
|
description,
|
||||||
url: `https://blog.wypark.me/posts/${slug}`,
|
url: canonicalUrl,
|
||||||
siteName: 'WYPark Blog',
|
siteName: SITE_NAME,
|
||||||
images: [{ url: imageUrl, width: 1200, height: 630 }],
|
images: [{ url: imageUrl, width: 1200, height: 630 }],
|
||||||
type: 'article',
|
type: 'article',
|
||||||
publishedTime: post.createdAt, // created_at 대신 createdAt 사용 주의 (타입 정의 따름)
|
publishedTime,
|
||||||
|
modifiedTime,
|
||||||
authors: ['WYPark'],
|
authors: ['WYPark'],
|
||||||
},
|
},
|
||||||
twitter: {
|
twitter: {
|
||||||
card: 'summary_large_image',
|
card: 'summary_large_image',
|
||||||
title: post.title,
|
title: post.title,
|
||||||
description: description,
|
description,
|
||||||
images: [imageUrl],
|
images: [imageUrl],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🌟 실제 페이지 렌더링 (SSR 적용)
|
|
||||||
export default async function PostDetailPage({ params }: Props) {
|
export default async function PostDetailPage({ params }: Props) {
|
||||||
const { slug } = await params;
|
const { slug } = await params;
|
||||||
|
const post = await fetchPublicPost(slug);
|
||||||
|
|
||||||
// 1. 서버에서 데이터를 미리 가져옵니다.
|
|
||||||
const post = await getPostFromServer(slug);
|
|
||||||
|
|
||||||
// 2. 데이터가 없으면 404 페이지로 보냅니다. (봇에게도 404 신호를 줌)
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
notFound();
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 가져온 데이터를 클라이언트 컴포넌트에 'initialPost'로 넘겨줍니다.
|
|
||||||
return <PostDetailClient slug={slug} initialPost={post} />;
|
return <PostDetailClient slug={slug} initialPost={post} />;
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
import { MetadataRoute } from 'next';
|
import { MetadataRoute } from 'next';
|
||||||
|
import { SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
export default function robots(): MetadataRoute.Robots {
|
export default function robots(): MetadataRoute.Robots {
|
||||||
const baseUrl = 'https://blog.wypark.me';
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
rules: {
|
rules: {
|
||||||
userAgent: '*',
|
userAgent: '*',
|
||||||
allow: '/',
|
allow: '/',
|
||||||
// 검색 로봇이 굳이 긁어갈 필요 없는 페이지들은 차단 (글쓰기, 로그인 등)
|
|
||||||
disallow: ['/write', '/login', '/signup', '/admin'],
|
disallow: ['/write', '/login', '/signup', '/admin'],
|
||||||
},
|
},
|
||||||
// 여기서 동적으로 생성된 sitemap.xml을 가리킵니다.
|
sitemap: `${SITE_URL}/sitemap.xml`,
|
||||||
sitemap: `${baseUrl}/sitemap.xml`,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,60 +1,40 @@
|
|||||||
import { MetadataRoute } from 'next';
|
import { MetadataRoute } from 'next';
|
||||||
|
import {
|
||||||
|
fetchPublicPosts,
|
||||||
|
} from '@/api/publicPosts';
|
||||||
|
import { parseApiDate, SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
interface SitemapPost {
|
export const dynamic = 'force-dynamic';
|
||||||
slug: string;
|
export const revalidate = 300;
|
||||||
updatedAt?: string;
|
|
||||||
createdAt?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||||
const baseUrl = 'https://blog.wypark.me';
|
const generatedAt = new Date();
|
||||||
// API 주소 환경변수 사용 (없으면 로컬)
|
|
||||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
|
|
||||||
|
|
||||||
// 1. 고정된 정적 페이지들
|
|
||||||
const routes: MetadataRoute.Sitemap = [
|
const routes: MetadataRoute.Sitemap = [
|
||||||
{
|
{
|
||||||
url: baseUrl,
|
url: SITE_URL,
|
||||||
lastModified: new Date(),
|
lastModified: generatedAt,
|
||||||
changeFrequency: 'daily',
|
changeFrequency: 'daily',
|
||||||
priority: 1,
|
priority: 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: `${baseUrl}/archive`,
|
url: `${SITE_URL}/archive`,
|
||||||
lastModified: new Date(),
|
lastModified: generatedAt,
|
||||||
changeFrequency: 'daily',
|
changeFrequency: 'daily',
|
||||||
priority: 0.8,
|
priority: 0.8,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
try {
|
const postsData = await fetchPublicPosts({ size: 1000, sort: 'createdAt,desc' });
|
||||||
// 2. API에서 게시글 목록 가져오기
|
const posts = postsData?.content || [];
|
||||||
const response = await fetch(`${apiUrl}/api/posts?size=1000&sort=createdAt,desc`, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
next: { revalidate: 3600 }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
const postRoutes: MetadataRoute.Sitemap = posts
|
||||||
throw new Error('Failed to fetch posts');
|
.filter((post) => post.slug)
|
||||||
}
|
.map((post) => ({
|
||||||
|
url: `${SITE_URL}/posts/${encodeURIComponent(post.slug)}`,
|
||||||
const json = await response.json() as { data?: { content?: SitemapPost[] } };
|
lastModified: parseApiDate(post.updatedAt || post.createdAt, generatedAt),
|
||||||
const posts = json.data?.content || [];
|
changeFrequency: 'weekly',
|
||||||
|
|
||||||
// 3. 게시글 데이터를 사이트맵 형식으로 변환
|
|
||||||
const postRoutes = posts.map((post) => ({
|
|
||||||
// 🛠️ 핵심 수정: slug를 encodeURIComponent로 감싸서 특수문자(&, 한글 등)를 안전하게 처리합니다.
|
|
||||||
url: `${baseUrl}/posts/${encodeURIComponent(post.slug)}`,
|
|
||||||
lastModified: new Date(post.updatedAt || post.createdAt || Date.now()),
|
|
||||||
changeFrequency: 'weekly' as const,
|
|
||||||
priority: 0.8,
|
priority: 0.8,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return [...routes, ...postRoutes];
|
return [...routes, ...postRoutes];
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Sitemap generation error:', error);
|
|
||||||
return routes;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
33
src/lib/site.ts
Normal file
33
src/lib/site.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
export const SITE_URL = 'https://blog.wypark.me';
|
||||||
|
export const SITE_NAME = 'WYPark Blog';
|
||||||
|
export const DEFAULT_DESCRIPTION = '개발 블로그';
|
||||||
|
|
||||||
|
const API_DATE_TIMEZONE = '+09:00';
|
||||||
|
const TIMEZONE_SUFFIX_PATTERN = /(z|[+-]\d{2}:?\d{2})$/i;
|
||||||
|
|
||||||
|
const trimSubMilliseconds = (value: string) => {
|
||||||
|
return value.replace(/(\.\d{3})\d+/, '$1');
|
||||||
|
};
|
||||||
|
|
||||||
|
const withApiTimezone = (value: string) => {
|
||||||
|
if (TIMEZONE_SUFFIX_PATTERN.test(value)) return value;
|
||||||
|
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00:00${API_DATE_TIMEZONE}`;
|
||||||
|
|
||||||
|
return `${value}${API_DATE_TIMEZONE}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCanonicalUrl = (path = '/') => {
|
||||||
|
return new URL(path, SITE_URL).toString();
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseApiDate = (value?: string | null, fallback = new Date()) => {
|
||||||
|
if (!value) return fallback;
|
||||||
|
|
||||||
|
const date = new Date(withApiTimezone(trimSubMilliseconds(value.trim())));
|
||||||
|
|
||||||
|
if (Number.isNaN(date.getTime())) return fallback;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
return date > now ? now : date;
|
||||||
|
};
|
||||||
|
|
||||||
Reference in New Issue
Block a user