Home > Web Front-end > JS Tutorial > How to build an Astro collection loader

How to build an Astro collection loader

Mary-Kate Olsen
Release: 2025-01-17 08:35:09
Original
142 people have browsed it

How to build an Astro collection loader

Astro's 1.14 release introduced the Content Layer API, extending content collections beyond local files. While Astro provides loaders for common data sources (RSS, CSV, etc.), creating custom loaders is straightforward. This guide demonstrates building a loader for a dad joke API.

Project Setup

Begin by creating a new Astro project:

<code class="language-bash">npm create astro@latest</code>
Copy after login

Follow the CLI prompts. Then start the development server:

<code class="language-bash">npm run dev</code>
Copy after login

Access your project at http://localhost:4321.

Enabling the Experimental API

The Content Layer API is experimental. Enable it by modifying astro.config.mjs:

<code class="language-javascript">// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
    experimental: {
        contentLayer: true,
    },
});</code>
Copy after login

Creating the Loader

Create a new file (e.g., src/loaders/jokes.ts) to house your loader. This example uses TypeScript, though it's not mandatory.

<code class="language-typescript">// src/loaders/jokes.ts
import type { Loader } from 'astro/loaders';

export const jokesLoader: Loader = {
    name: 'jokes',
    load: async (context) => {
        const response = await fetch('https://icanhazdadjoke.com/', {
            headers: {
                Accept: 'application/json',
            },
        });

        const json = await response.json();

        context.store.set({
            id: json.id,
            data: json,
        });
    },
};</code>
Copy after login

A loader comprises:

  • name (required): The loader's identifier.
  • load (required): The asynchronous function fetching and processing data. It receives a context object providing access to the data store and logger.
  • schema (optional): A Zod schema for data validation.

Connecting the Loader to a Collection

Create a configuration file (e.g., src/content/config.ts) to define your collection:

<code class="language-typescript">// src/content/config.ts
import { defineCollection } from 'astro:content';
import { jokesLoader } from '../loaders/jokes';

const jokes = defineCollection({
    loader: jokesLoader,
});

export const collections = {
    jokes,
};</code>
Copy after login

Accessing the Data

In an Astro component, access the data using getCollection:

<code class="language-astro">---
import { getCollection } from 'astro:content';

const jokes = await getCollection('jokes');
---

<ul>
  {jokes.map(joke => <li>{joke.data.joke}</li>)}
</ul></code>
Copy after login

Building and Running

Run npm run build. The loader will execute, fetching and storing the joke data. The Astro component will then display the fetched joke.

Conclusion

This illustrates building a basic Astro collection loader. This approach can be extended to handle more complex data sources and incorporate features like error handling and pagination. The modular design allows for creating reusable loaders, potentially packaging them for wider use.

The above is the detailed content of How to build an Astro collection loader. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template