Skip to content

Commit

Permalink
Fix file loader for JSON object files (#11801)
Browse files Browse the repository at this point in the history
* Add `filePath` to `file()` loader entries when JSON file is an object

* Add changeset
  • Loading branch information
delucis authored Aug 21, 2024
1 parent 6814ff0 commit 9f943c1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-rats-fail.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 4 additions & 6 deletions packages/astro/src/content/loaders/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand All @@ -39,19 +41,15 @@ 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<Record<string, unknown>>(json);
logger.debug(`Found object with ${entries.length} entries in ${fileName}`);
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.`);
Expand Down

0 comments on commit 9f943c1

Please sign in to comment.