Skip to content

Commit

Permalink
requested changes
Browse files Browse the repository at this point in the history
  • Loading branch information
rgodha24 committed Sep 23, 2024
1 parent 16a46cb commit d53d377
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
37 changes: 36 additions & 1 deletion .changeset/lovely-pianos-breathe.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
})
```
4 changes: 3 additions & 1 deletion packages/astro/src/content/loaders/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | Array<{ id: string } & Record<string, unknown>>;
}

/**
Expand Down

0 comments on commit d53d377

Please sign in to comment.