Skip to content

Commit

Permalink
[Fix] Post 페이지 동적 라우팅이 동작하지 않는다
Browse files Browse the repository at this point in the history
  • Loading branch information
junhyeok-clap committed Dec 23, 2024
1 parent 530c52a commit 117423c
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,44 @@ import { join } from "path";
const postsDirectory = join(process.cwd(), "_posts");

export function getPostSlugs() {
return fs.readdirSync(postsDirectory);
try {
return fs.readdirSync(postsDirectory);
} catch (error) {
console.error("Error reading post directory:", error);
return [];
}
}

export function getPostBySlug(slug: string) {
const realSlug = slug.replace(/\.md$/, "");
const fullPath = join(postsDirectory, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents);
try {
const realSlug = slug.replace(/\.md$/, "");
const fullPath = join(postsDirectory, `${realSlug}.md`);

return { ...data, slug: realSlug, content } as Post;
if (!fs.existsSync(fullPath)) {
throw new Error(`File not found: ${fullPath}`);
}

const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents);

return { ...data, slug: realSlug, content } as Post;
} catch (error) {
console.error(`Error getting post by slug ${slug}:`, error);
return null;
}
}

export function getAllPosts(): Post[] {
const slugs = getPostSlugs();
const posts = slugs
.map((slug) => getPostBySlug(slug))
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
return posts;
try {
const slugs = getPostSlugs();
const posts = slugs
.map((slug) => getPostBySlug(slug))
.filter((post): post is Post => post !== null) // null 값 제외
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));

return posts;
} catch (error) {
console.error("Error getting all posts:", error);
return [];
}
}

0 comments on commit 117423c

Please sign in to comment.