Skip to content

Commit

Permalink
feat: 스키마 검증(with zod)으로 any 타입 삭제
Browse files Browse the repository at this point in the history
  • Loading branch information
SaeWooKKang committed Jun 3, 2024
1 parent 1f4b465 commit 7fa3c70
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
12 changes: 2 additions & 10 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -30,7 +22,7 @@ export const getStaticProps = async () => {
};

function PostNames() {
const { data: postMetaList } = useSWR<Posts[]>(KEY_POST);
const { data: postMetaList } = useSWR<Array<PostMeta>>(KEY_POST);

return (
<ul>
Expand Down
22 changes: 19 additions & 3 deletions src/shared/service/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof metaDataSchema>;

export class PostService {
private static async markdownToHTML(markdown: string) {
const result = await remark()
Expand All @@ -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();
}

Expand Down

0 comments on commit 7fa3c70

Please sign in to comment.