1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-11-23 12:06:07 -05:00

refactor note processing functions

This commit is contained in:
2025-03-28 09:22:04 -04:00
parent 2d42a7447e
commit 264fd92379
7 changed files with 96 additions and 69 deletions

View File

@@ -19,46 +19,8 @@ export type FrontMatter = {
noComments?: boolean;
};
// returns front matter and the **raw & uncompiled** markdown of a given slug
export const getFrontMatter = cache(async (slug: string): Promise<FrontMatter | undefined> => {
try {
const { frontmatter } = await import(`../../${POSTS_DIR}/${slug}/index.mdx`);
// process markdown title to html...
const htmlTitle = await unified()
.use(remarkParse)
.use(remarkSmartypants)
.use(remarkHtml, {
sanitize: {
// allow *very* limited markdown to be used in post titles
tagNames: ["code", "em", "strong"],
},
})
.process(frontmatter.title)
.then((result) => result.toString().trim());
// ...and then (sketchily) remove said html for a plaintext version:
// https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
const title = decode(htmlTitle.replace(/<[^>]*>/g, ""));
return {
...(frontmatter as Partial<FrontMatter>),
// plain title without html or markdown syntax:
title,
// stylized title with limited html tags:
htmlTitle,
slug,
date: new Date(frontmatter.date).toISOString(), // validate/normalize the date string provided from front matter
permalink: `${BASE_URL}/${POSTS_DIR}/${slug}`,
};
} catch (error) {
console.error(`Failed to load front matter for post with slug "${slug}":`, error);
return undefined;
}
});
// use filesystem to get a simple list of all post slugs
export const getPostSlugs = cache(async (): Promise<string[]> => {
/** Use filesystem to get a simple list of all post slugs */
export const getSlugs = cache(async (): Promise<string[]> => {
// list all .mdx files in POSTS_DIR
const mdxFiles = await glob("*/index.mdx", {
cwd: path.join(process.cwd(), POSTS_DIR),
@@ -71,10 +33,76 @@ export const getPostSlugs = cache(async (): Promise<string[]> => {
return slugs;
});
// returns the content of a post with very limited processing to include in RSS feeds
// TODO: also remove MDX-related syntax (e.g. import/export statements)
export const getPostContent = cache(async (slug: string): Promise<string | undefined> => {
// overloaded to return either the front matter of a single post or ALL posts
export const getFrontMatter: {
/**
* Parses and returns the front matter of ALL posts, sorted reverse chronologically
*/
(): Promise<FrontMatter[]>;
/**
* Parses and returns the front matter of a given slug, or undefined if the slug does not exist
*/
(slug: string): Promise<FrontMatter | undefined>;
} = cache(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (slug?: any): Promise<any> => {
if (typeof slug === "string") {
try {
const { frontmatter } = await import(`../../${POSTS_DIR}/${slug}/index.mdx`);
// process markdown title to html...
const htmlTitle = await unified()
.use(remarkParse)
.use(remarkSmartypants)
.use(remarkHtml, {
sanitize: {
// allow *very* limited markdown to be used in post titles
tagNames: ["code", "em", "strong"],
},
})
.process(frontmatter.title)
.then((result) => result.toString().trim());
// ...and then (sketchily) remove said html for a plaintext version:
// https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
const title = decode(htmlTitle.replace(/<[^>]*>/g, ""));
return {
...(frontmatter as Partial<FrontMatter>),
// plain title without html or markdown syntax:
title,
// stylized title with limited html tags:
htmlTitle,
slug,
// validate/normalize the date string provided from front matter
date: new Date(frontmatter.date).toISOString(),
permalink: `${BASE_URL}/${POSTS_DIR}/${slug}`,
} as FrontMatter;
} catch (error) {
console.error(`Failed to load front matter for post with slug "${slug}":`, error);
return undefined;
}
}
if (!slug) {
// concurrently fetch the front matter of each post
const slugs = await getSlugs();
const posts = await Promise.all(slugs.map(getFrontMatter));
// sort the results reverse chronologically and return
return posts.sort(
(post1, post2) => new Date(post2!.date).getTime() - new Date(post1!.date).getTime()
) as FrontMatter[];
}
throw new Error(`getFrontMatter() called with invalid argument.`);
}
);
/** Returns the content of a post with very limited processing to include in RSS feeds */
export const getContent = cache(async (slug: string): Promise<string | undefined> => {
try {
// TODO: also remove MDX-related syntax (e.g. import/export statements)
const content = await unified()
.use(remarkParse)
.use(remarkFrontmatter)
@@ -104,20 +132,10 @@ export const getPostContent = cache(async (slug: string): Promise<string | undef
})
.process(await read(path.resolve(process.cwd(), `${POSTS_DIR}/${slug}/index.mdx`)));
// convert the parsed content to a string
return content.toString().trim();
// convert the parsed content to a string with "safe" HTML
return content.toString().replaceAll("<p></p>", "").trim();
} catch (error) {
console.error(`Failed to load/parse content for post with slug "${slug}":`, error);
return undefined;
}
});
// returns the parsed front matter of ALL posts, sorted reverse chronologically
export const getAllPosts = cache(async (): Promise<FrontMatter[]> => {
// concurrently fetch the front matter of each post
const slugs = await getPostSlugs();
const posts = (await Promise.all(slugs.map(getFrontMatter))) as FrontMatter[];
// sort the results reverse chronologically and return
return posts.sort((post1, post2) => new Date(post1.date).getTime() - new Date(post2.date).getTime());
});