-
Notifications
You must be signed in to change notification settings - Fork 0
/
posts.ts
42 lines (34 loc) · 947 Bytes
/
posts.ts
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
31
32
33
34
35
36
37
38
39
40
41
42
import fs from 'fs';
import { join } from 'path';
const postsDirectory = join(process.cwd(), 'src/pages/blog');
export type Post = {
slug: string;
title: string;
date: string;
};
export const getAllPostsSlug = () => {
return (
fs
.readdirSync(postsDirectory)
// ignore index file
.filter((filename) => filename !== 'index.tsx')
// remove .mdx extension from filename
.map((filename) => filename.replace(/\.mdx$/, ''))
);
};
export const getPostBySlug = (slug: string): Post => {
const pageModule = require(`../pages/blog/${slug}.mdx`);
return {
slug,
title: pageModule.meta.title,
date: pageModule.meta.date,
};
};
export const getAllPosts = () => {
const slugs = getAllPostsSlug();
const posts = slugs
.map((slug) => getPostBySlug(slug))
// sort posts by date in descending order
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
return posts;
};