1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import fs from "fs"; import { join } from "path"; import matter from "gray-matter"; const postsDir = join(process.cwd(), "posts");
type MetaData = { title: string; date: Date; updated: Date; tags?: string[]; categories?: string[]; cover: string; descr?: string; draft?: boolean; };
export function getPostBySlug(slug: string) { const realSlug = slug.replace(/\.md$/, ""); const fullPath = join(postsDir, `${realSlug}.md`); const fileContents = fs.readFileSync(fullPath, "utf8"); const { data, content, excerpt } = matter(fileContents, { excerpt: true, }); const meta = { ...data } as MetaData; return { slug: realSlug, meta, content, excerpt }; }
export function getAllPosts() { const slugs = fs.readdirSync(postsDir); const posts = slugs.map((slug) => getPostBySlug(slug)).filter((c) => !/\.draft$/.test(c.slug)); return posts.sort((a, b) => +b.meta.date - +a.meta.date); }
|