-
Notifications
You must be signed in to change notification settings - Fork 0
/
blog.ts
93 lines (76 loc) · 2.55 KB
/
blog.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { join } from "path";
import matter from "gray-matter";
import { z } from "zod";
import fs from "fs";
import path from "path";
import { Feed } from "feed";
export async function generateRssFeed() {
const allPosts = getAllPosts();
const site_url = "https://www.walterkjenkins.com/";
const feedOptions = {
title: "Blog posts | RSS Feed",
description: "Welcome to this blog posts!",
id: site_url,
link: site_url,
image: `${site_url}/logo.png`,
favicon: `${site_url}/favicon.png`,
copyright: `All rights reserved ${new Date().getFullYear()}, Ibas`,
generator: "Feed for Node.js",
feedLinks: {
rss2: `${site_url}/rss.xml`,
// other feed formats
json: `${site_url}/rss.json`,
atom: `${site_url}/atom.xml`,
},
};
const feed = new Feed(feedOptions);
allPosts.forEach((post) => {
feed.addItem({
title: post.title,
id: `${site_url}/blog/${post.slug}`,
link: `${site_url}/blog/${post.slug}`,
description: post.excerpt,
date: new Date(post.date),
});
});
fs.writeFileSync("./public/blog/rss.xml", feed.rss2());
// write other feed formats to public folder
fs.writeFileSync("./public/blog/rss.json", feed.json1());
fs.writeFileSync("./public/blog/atom.xml", feed.atom1());
}
export const POSTS_PATH = path.join(process.cwd(), "_posts");
// postFilePaths is the list of all mdx files inside the POSTS_PATH directory
export const postFilePaths = fs
.readdirSync(POSTS_PATH)
// Only include md(x) files
.filter((path) => /\.mdx?$/.test(path));
export const zBlogMeta = z.object({
title: z.string(),
slug: z.string(),
date: z.string(),
author: z.object({ name: z.string(), picture: z.string() }),
coverImage: z.string(),
excerpt: z.string(),
tags: z.array(z.string()),
ogImage: z.string(),
});
export type BlogMetaType = z.infer<typeof zBlogMeta>;
const postsDirectory = join(process.cwd(), "_posts");
export function getPostSlugs() {
return fs.readdirSync(postsDirectory).filter((val) => val.endsWith(".mdx"));
}
export function getPostBySlug(slug: string) {
const realSlug = slug.replace(/\.mdx$/, "");
const fullPath = join(postsDirectory, `${realSlug}.mdx`);
const source = fs.readFileSync(fullPath);
const { data } = matter(source);
return zBlogMeta.parse({ ...data, slug: realSlug });
}
export function getAllPosts() {
const slugs = getPostSlugs();
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;
}