From d53d37706cce5b0764a40689d45935147e26c528 Mon Sep 17 00:00:00 2001 From: Rohan Godha Date: Mon, 23 Sep 2024 12:44:40 -0400 Subject: [PATCH] requested changes --- .changeset/lovely-pianos-breathe.md | 37 +++++++++++++++++++++- packages/astro/src/content/loaders/file.ts | 4 ++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/.changeset/lovely-pianos-breathe.md b/.changeset/lovely-pianos-breathe.md index 0a81675ef999..93d5f56fc54d 100644 --- a/.changeset/lovely-pianos-breathe.md +++ b/.changeset/lovely-pianos-breathe.md @@ -2,4 +2,39 @@ 'astro': minor --- -feat: custom file formats in astro/loader/file.ts +Adds support for custom parsers to file loader + +For example, with a toml file of this format: +```toml +[[dogs]] +id = "..." +age = "..." + +[[dogs]] +id = "..." +age = "..." +``` +a content collection using this file could look like this +```typescript +import { defineCollection } from "astro:content" +import { file } from "astro/loaders" +import { parse as parseToml } from "toml" +const dogs = defineCollection({ + loader: file("src/data/dogs.toml", { parser: (text) => parseToml(text).dogs }), + schema: /* ... */ +}) +``` + +This also adds support for nested json documents. For example: +```json +{"dogs": [{}], "cats": [{}]} +``` +can be consumed using +```typescript +const dogs = defineCollection({ + loader: file("src/data/pets.json", { parser: (text) => JSON.parse(text).dogs }) +}) +const cats = defineCollection({ + loader: file("src/data/pets.json", { parser: (text) => JSON.parse(text).cats }) +}) +``` diff --git a/packages/astro/src/content/loaders/file.ts b/packages/astro/src/content/loaders/file.ts index 2b387246e3f2..ed1701e11108 100644 --- a/packages/astro/src/content/loaders/file.ts +++ b/packages/astro/src/content/loaders/file.ts @@ -9,7 +9,9 @@ export interface FileOptions { * the parsing function to use for this data * @default JSON.parse or yaml.load, depending on the extension of the file * */ - parser?: (text: string) => any; + parser?: ( + text: string, + ) => Record | Array<{ id: string } & Record>; } /**