1
1
mirror of https://github.com/theoludwig/theoludwig.git synced 2024-11-05 04:51:30 +01:00
.profile/blog/blog.ts

66 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-07-01 23:12:47 +02:00
import fs from 'node:fs'
import path from 'node:path'
2021-11-08 15:10:26 +01:00
import { cache } from 'react'
2021-11-08 15:10:26 +01:00
import matter from 'gray-matter'
2023-08-01 18:59:45 +02:00
export const BLOG_POSTS_PATH = path.join(process.cwd(), 'blog', 'posts')
2021-11-08 15:10:26 +01:00
export interface FrontMatter {
title: string
description: string
isPublished: boolean
publishedOn: string
}
2023-08-01 18:59:45 +02:00
export interface BlogPost {
2021-11-08 15:10:26 +01:00
frontmatter: FrontMatter
slug: string
content: string
}
2023-08-01 18:59:45 +02:00
export const getBlogPosts = cache(async (): Promise<BlogPost[]> => {
const blogPosts = await fs.promises.readdir(BLOG_POSTS_PATH)
const blogPostsWithTime = await Promise.all(
blogPosts.map(async (blogPostFilename) => {
const [slug, extension] = blogPostFilename.split('.')
2023-01-10 23:56:46 +01:00
if (slug == null || extension == null) {
2023-08-01 18:59:45 +02:00
throw new Error('Invalid blog post filename.')
2023-01-10 23:56:46 +01:00
}
2023-08-01 18:59:45 +02:00
const blogPostPath = path.join(BLOG_POSTS_PATH, `${slug}.${extension}`)
2021-11-08 15:10:26 +01:00
const blogPostContent = await fs.promises.readFile(blogPostPath, {
encoding: 'utf8'
})
const { data, content } = matter(blogPostContent) as unknown as {
data: FrontMatter
content: string
}
2021-11-08 15:10:26 +01:00
const date = new Date(data.publishedOn)
return {
slug,
content,
frontmatter: data,
time: date.getTime()
}
})
)
2023-08-01 18:59:45 +02:00
const blogPostsSortedByPublicationDate = blogPostsWithTime
2022-09-04 20:40:58 +02:00
.filter((post) => {
return post.frontmatter.isPublished
})
.sort((a, b) => {
return b.time - a.time
})
2023-08-01 18:59:45 +02:00
return blogPostsSortedByPublicationDate
})
2021-11-08 15:10:26 +01:00
2023-08-01 17:44:08 +02:00
export const getBlogPostBySlug = cache(
2023-08-01 18:59:45 +02:00
async (slug: string): Promise<BlogPost | undefined> => {
const blogPosts = await getBlogPosts()
const blogPost = blogPosts.find((blogPost) => {
return blogPost.slug === slug && blogPost.frontmatter.isPublished
})
2023-08-01 18:59:45 +02:00
return blogPost
2021-11-08 15:10:26 +01:00
}
)