From 446d5a31eedf3161e83139e1fdacc14fa9ee4307 Mon Sep 17 00:00:00 2001 From: mateonunez Date: Thu, 25 Jan 2024 10:53:07 -0500 Subject: [PATCH] perf(parser): add compiled source cache Signed-off-by: mateonunez --- lib/articles/parser.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/articles/parser.js b/lib/articles/parser.js index 4fbc4df..fc4534d 100644 --- a/lib/articles/parser.js +++ b/lib/articles/parser.js @@ -5,6 +5,10 @@ import removeMarkdown from 'remove-markdown'; import readingTime from 'reading-time'; import config from 'lib/config'; import { serialize } from 'next-mdx-remote/serialize'; +// import remarkGfm from 'remark-gfm'; +import rehypeSlug from 'rehype-slug'; +import rehypePrism from 'rehype-prism-plus'; + export function getArticleSlugs() { const fullPath = path.join(process.cwd(), './articles'); @@ -65,7 +69,7 @@ function parseArticleData({ raw, slug = '' }) { export async function getArticle({ slug }) { const { frontMatter, content } = getArticleData({ slug }); - const compiledSource = await compileSource({ content }); + const compiledSource = await compileSource({ content, slug }); const article = { frontMatter, source: compiledSource, @@ -73,13 +77,25 @@ export async function getArticle({ slug }) { return article; } - +// const remarkPlugins = [[remarkGfm]]; +const rehypePlugins = [[rehypeSlug], [rehypePrism, { ignoreMissing: true }]]; const serializeOptions = { parserFormatter: false, + mdxOptions: { + // remarkPlugins, is not compatible with the current mdx-js version + rehypePlugins, + }, } -async function compileSource({ content }) { - const { compiledSource } = await serialize(content, serializeOptions); +const compiledSourcesCached = new Map() +async function compileSource({ content, slug }) { + const isCompiledSourceCached = compiledSourcesCached.has(slug); + if (isCompiledSourceCached) { + console.log('hit!'); + return compiledSourcesCached.get(slug); + } + const { compiledSource } = await serialize(content, serializeOptions); + compiledSourcesCached.set(slug, compiledSource); return compiledSource; }