From 9f943c1344671b569a0d1ddba683b3cca0068adc Mon Sep 17 00:00:00 2001 From: Chris Swithinbank Date: Wed, 21 Aug 2024 13:17:52 +0200 Subject: [PATCH] Fix file loader for JSON object files (#11801) * Add `filePath` to `file()` loader entries when JSON file is an object * Add changeset --- .changeset/four-rats-fail.md | 5 +++++ packages/astro/src/content/loaders/file.ts | 10 ++++------ 2 files changed, 9 insertions(+), 6 deletions(-) create mode 100644 .changeset/four-rats-fail.md diff --git a/.changeset/four-rats-fail.md b/.changeset/four-rats-fail.md new file mode 100644 index 000000000000..aa0fcbdb71b4 --- /dev/null +++ b/.changeset/four-rats-fail.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes a bug where the `filePath` property was not available on content collection entries when using the content layer `file()` loader with a JSON file that contained an object instead of an array. This was breaking use of the `image()` schema utility among other things. diff --git a/packages/astro/src/content/loaders/file.ts b/packages/astro/src/content/loaders/file.ts index cbc684a99788..75e5e214d9a8 100644 --- a/packages/astro/src/content/loaders/file.ts +++ b/packages/astro/src/content/loaders/file.ts @@ -26,6 +26,8 @@ export function file(fileName: string): Loader { return; } + const normalizedFilePath = posixRelative(fileURLToPath(settings.config.root), filePath); + if (Array.isArray(json)) { if (json.length === 0) { logger.warn(`No items found in ${fileName}`); @@ -39,11 +41,7 @@ export function file(fileName: string): Loader { continue; } const data = await parseData({ id, data: rawItem, filePath }); - store.set({ - id, - data, - filePath: posixRelative(fileURLToPath(settings.config.root), filePath), - }); + store.set({ id, data, filePath: normalizedFilePath }); } } else if (typeof json === 'object') { const entries = Object.entries>(json); @@ -51,7 +49,7 @@ export function file(fileName: string): Loader { store.clear(); for (const [id, rawItem] of entries) { const data = await parseData({ id, data: rawItem, filePath }); - store.set({ id, data }); + store.set({ id, data, filePath: normalizedFilePath }); } } else { logger.error(`Invalid data in ${fileName}. Must be an array or object.`);