web-portfolio/lib/articles.ts

74 lines
2.1 KiB
TypeScript
Raw Normal View History

2026-07-16 16:41:56 -05:00
import fs from "fs"
import matter from "gray-matter"
import path from "path"
import moment from "moment"
import {remark} from "remark";
import html from "remark-html"
import type {ArticleItem} from "@/types";
const articlesDirectory = path.join(process.cwd(), "articles");
2026-08-05 10:43:13 -05:00
export const getSortedArticles = (): ArticleItem[] => {
2026-07-16 16:41:56 -05:00
const fileNames = fs.readdirSync(articlesDirectory);
const allArticlesData = fileNames.map((fileName) => {
const id = fileName.replace(/\.md$/, "");
const fullPath = path.join(articlesDirectory, fileName);
const fileContents = fs.readFileSync(fullPath, "utf8");
const matterResult = matter(fileContents);
return {
id,
title: matterResult.data.title,
date: matterResult.data.date,
category: matterResult.data.category,
}
})
return allArticlesData.sort((a, b) => {
const format = "DD-MM-YYYY";
const dateOne = moment(a.date, format);
const dateTwo = moment(b.date, format);
return dateTwo.valueOf() - dateOne.valueOf();
})
}
export const getCategorizedArticles = (): Record<string, ArticleItem[]> => {
const sortedArticles = getSortedArticles();
const categorisedArticles: Record<string, ArticleItem[]> = {}
sortedArticles.forEach((article) => {
if (!categorisedArticles[article.category]) {
categorisedArticles[article.category] = []
}
categorisedArticles[article.category].push(article);
})
return categorisedArticles;
}
export const getArticleData = async (id: string) => {
const fullPath = path.join(articlesDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const matterResult = matter(fileContents);
const processedContent = await remark()
.use(html)
.process(matterResult.content)
const contentHtml = processedContent.toString();
return {
id,
contentHtml,
title: matterResult.data.title,
category: matterResult.data.category,
date: moment(matterResult.data.date, "DD-MM-YYYY").format("MMMM Do YYYY")
}
}