From eee0a1da45a658e806ebc41d90d0d1b7cb1d712c Mon Sep 17 00:00:00 2001 From: jaeyoung Date: Mon, 3 Jun 2024 23:15:01 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=8A=A4=ED=82=A4=EB=A7=88=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D(with=20zod)=EC=9C=BC=EB=A1=9C=20any=20=ED=83=80?= =?UTF-8?q?=EC=9E=85=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/index.tsx | 12 ++---------- src/shared/service/post.service.ts | 22 +++++++++++++++++++--- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 2c33b9b..fbf8986 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -3,20 +3,12 @@ import useSWR from 'swr'; import Layout from '../shared/component/layout'; import { + type PostMeta, PostService, } from '../shared/service/post.service'; const KEY_POST = '/api/posts'; -interface Posts { - title: string; - date: string; - description: string; - thumbnail: string; - slug: string; - keyword: string; -} - export const getStaticProps = async () => { const postMetaList = await PostService.getMetaList(); @@ -30,7 +22,7 @@ export const getStaticProps = async () => { }; function PostNames() { - const { data: postMetaList } = useSWR(KEY_POST); + const { data: postMetaList } = useSWR>(KEY_POST); return (
    diff --git a/src/shared/service/post.service.ts b/src/shared/service/post.service.ts index ce4909a..99df6ac 100644 --- a/src/shared/service/post.service.ts +++ b/src/shared/service/post.service.ts @@ -3,8 +3,20 @@ import { remark } from 'remark'; import html from 'remark-html'; import remarkPrism from 'remark-prism'; import path from 'path'; +import { z } from 'zod'; import { File } from '../../common/util/fs'; +const metaDataSchema = z.object({ + title: z.string(), + date: z.string(), + description: z.string(), + thumbnail: z.string().optional(), + slug: z.string(), + keyword: z.string(), +}); + +export type PostMeta = z.infer; + export class PostService { private static async markdownToHTML(markdown: string) { const result = await remark() @@ -26,12 +38,16 @@ export class PostService { const md = this.getPostFile(id); const { data: meta, content } = matter(md); - const parsedContent = { meta, html: content }; + try { + const parsedContent = { meta: metaDataSchema.parse(meta), html: content }; - return parsedContent; + return parsedContent; + } catch (error) { + throw new Error(`ID: ${id}의 메타 데이터 파싱에 실패했습니다. ${error}`); + } } - private static sortByDescendingForFileName(a: any, b: any) { + private static sortByDescendingForFileName(a:PostMeta, b: PostMeta) { return new Date(b.date).getTime() - new Date(a.date).getTime(); }