From 1c3bfdc6b32450fab56f80cc840193b6a46c8776 Mon Sep 17 00:00:00 2001 From: bholmesdev Date: Thu, 27 Apr 2023 12:34:30 -0400 Subject: [PATCH] refactor: add cache layer --- packages/astro/src/content/types-generator.ts | 2 ++ packages/astro/src/content/utils.ts | 15 +++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index d63afd812..b2da3a9d9 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -202,6 +202,7 @@ export async function createContentTypesGenerator({ fileUrl: event.entry, contentEntryType, fs, + invalidateCache: true, }); if (!(collectionKey in contentTypes)) { addCollection(contentTypes, collectionKey); @@ -225,6 +226,7 @@ export async function createContentTypesGenerator({ fileUrl: event.entry, contentEntryType, fs, + invalidateCache: true, }); if (contentTypes[collectionKey]?.[entryKey]?.slug !== changedSlug) { setEntry(contentTypes, collectionKey, entryKey, changedSlug); diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index 2a9e41689..ba2a93f04 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -442,6 +442,7 @@ export async function getStringifiedLookupMap({ return JSON.stringify(filePathByLookupId); } +const frontmatterSlugCache = new Map(); /** * Check for slug in content entry frontmatter and validate the type, * falling back to the `generatedSlug` if none is found. @@ -453,6 +454,7 @@ export async function getEntrySlug({ contentEntryType, fileUrl, fs, + invalidateCache = false, }: { fs: typeof fsMod; id: string; @@ -460,11 +462,16 @@ export async function getEntrySlug({ generatedSlug: string; fileUrl: URL; contentEntryType: Pick; + invalidateCache?: boolean; }) { - const { slug: frontmatterSlug } = await contentEntryType.getEntryInfo({ - fileUrl, - contents: await fs.promises.readFile(fileUrl, 'utf-8'), - }); + if (!frontmatterSlugCache.has(id) || invalidateCache) { + const { slug: frontmatterSlug } = await contentEntryType.getEntryInfo({ + fileUrl, + contents: await fs.promises.readFile(fileUrl, 'utf-8'), + }); + frontmatterSlugCache.set(id, frontmatterSlug); + } + const frontmatterSlug = frontmatterSlugCache.get(id); return parseEntrySlug({ generatedSlug, frontmatterSlug, id, collection }); }