Skip to content

Commit 7aee734

Browse files
[Fix] Post 페이지 동적 라우팅이 동작하지 않는다
[Fix] Post 페이지 동적 라우팅이 동작하지 않는다
2 parents 530c52a + 117423c commit 7aee734

File tree

1 file changed

+33
-11
lines changed

1 file changed

+33
-11
lines changed

src/lib/api.ts

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,44 @@ import { join } from "path";
66
const postsDirectory = join(process.cwd(), "_posts");
77

88
export function getPostSlugs() {
9-
return fs.readdirSync(postsDirectory);
9+
try {
10+
return fs.readdirSync(postsDirectory);
11+
} catch (error) {
12+
console.error("Error reading post directory:", error);
13+
return [];
14+
}
1015
}
1116

1217
export function getPostBySlug(slug: string) {
13-
const realSlug = slug.replace(/\.md$/, "");
14-
const fullPath = join(postsDirectory, `${realSlug}.md`);
15-
const fileContents = fs.readFileSync(fullPath, "utf8");
16-
const { data, content } = matter(fileContents);
18+
try {
19+
const realSlug = slug.replace(/\.md$/, "");
20+
const fullPath = join(postsDirectory, `${realSlug}.md`);
1721

18-
return { ...data, slug: realSlug, content } as Post;
22+
if (!fs.existsSync(fullPath)) {
23+
throw new Error(`File not found: ${fullPath}`);
24+
}
25+
26+
const fileContents = fs.readFileSync(fullPath, "utf8");
27+
const { data, content } = matter(fileContents);
28+
29+
return { ...data, slug: realSlug, content } as Post;
30+
} catch (error) {
31+
console.error(`Error getting post by slug ${slug}:`, error);
32+
return null;
33+
}
1934
}
2035

2136
export function getAllPosts(): Post[] {
22-
const slugs = getPostSlugs();
23-
const posts = slugs
24-
.map((slug) => getPostBySlug(slug))
25-
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
26-
return posts;
37+
try {
38+
const slugs = getPostSlugs();
39+
const posts = slugs
40+
.map((slug) => getPostBySlug(slug))
41+
.filter((post): post is Post => post !== null) // null 값 제외
42+
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
43+
44+
return posts;
45+
} catch (error) {
46+
console.error("Error getting all posts:", error);
47+
return [];
48+
}
2749
}

0 commit comments

Comments
 (0)