Commit e760d2e

HPCesia <me@hpcesia.com>
2025-02-10 12:52:59
refactor: move render cache to content utils
1 parent 3ab4d4c
Changed files (3)
src/pages/posts/[article].astro
@@ -7,7 +7,7 @@ import License from '@components/misc/License.astro';
 import PostInfo from '@components/misc/PostInfo.astro';
 import Markdown from '@components/utils/Markdown.astro';
 import GridLayout from '@layouts/GridLayout.astro';
-import { getOrCreateRenderResult } from '@utils/component-utils';
+import { getOrCreateRenderResult } from '@utils/content-utils';
 import { getCollection } from 'astro:content';
 
 export async function getStaticPaths() {
src/utils/component-utils.ts
@@ -1,6 +1,4 @@
-import type { AstroGlobal, MarkdownHeading } from 'astro';
-import type { AstroComponentFactory } from 'astro/runtime/server/index.js';
-import { type CollectionEntry, render } from 'astro:content';
+import type { AstroGlobal } from 'astro';
 
 const renderedInstance = new Set<string>();
 
@@ -12,25 +10,3 @@ export function isFirstInstance(id: string, url: AstroGlobal['url']): boolean {
   renderedInstance.add(key);
   return true;
 }
-
-interface RenderResult {
-  Content: AstroComponentFactory;
-  headings: MarkdownHeading[];
-  remarkPluginFrontmatter: Record<string, unknown>;
-}
-
-const renderCache = new Map<string, RenderResult>();
-
-export async function getOrCreateRenderResult(article: CollectionEntry<'posts'>) {
-  const cacheKey = article.id;
-
-  if (renderCache.has(cacheKey)) {
-    return renderCache.get(cacheKey)!;
-  }
-
-  const { Content, headings, remarkPluginFrontmatter } = await render(article);
-  const result = { Content, headings, remarkPluginFrontmatter };
-
-  renderCache.set(cacheKey, result);
-  return result;
-}
src/utils/content-utils.ts
@@ -1,7 +1,32 @@
 import type { BlogPostData } from '@/types/data';
 import I18nKey from '@i18n/I18nKey';
 import { i18n } from '@i18n/translation';
+import type { MarkdownHeading } from 'astro';
+import type { AstroComponentFactory } from 'astro/runtime/server/index.js';
 import { getCollection } from 'astro:content';
+import { type CollectionEntry, render } from 'astro:content';
+
+interface RenderResult {
+  Content: AstroComponentFactory;
+  headings: MarkdownHeading[];
+  remarkPluginFrontmatter: Record<string, unknown>;
+}
+
+const renderCache = new Map<string, RenderResult>();
+
+export async function getOrCreateRenderResult(article: CollectionEntry<'posts'>) {
+  const cacheKey = article.id;
+
+  if (renderCache.has(cacheKey)) {
+    return renderCache.get(cacheKey)!;
+  }
+
+  const { Content, headings, remarkPluginFrontmatter } = await render(article);
+  const result = { Content, headings, remarkPluginFrontmatter };
+
+  renderCache.set(cacheKey, result);
+  return result;
+}
 
 export async function getSortedPosts(): Promise<{ body: string; data: BlogPostData }[]> {
   const allBlogPosts = (await getCollection('posts')) as unknown as {