@@ -6,22 +6,44 @@ import { join } from "path";
66const postsDirectory = join ( process . cwd ( ) , "_posts" ) ;
77
88export 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
1217export function getPostBySlug ( slug : string ) {
13- const realSlug = slug . replace ( / \. m d $ / , "" ) ;
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 ( / \. m d $ / , "" ) ;
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
2136export 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