Referencia de la API de Colecciones de Contenido
Agregado en:
astro@2.0.0
Las colecciones de contenido en tiempo de build ofrecen APIs para configurar, consultar y renderizar tus archivos locales Markdown, MDX, Markdoc, YAML, TOML o JSON, así como contenido remoto.
Añadido en:
astro@6.0.0
Las colecciones de contenido live ofrecen APIs para configurar, consultar y renderizar datos live frescos y actualizados desde fuentes remotas.
Para características y ejemplos de uso, consulta nuestra guía de colecciones de contenido.
Importaciones desde astro:content
Sección titulada “Importaciones desde astro:content”import { defineCollection, defineLiveCollection, getCollection, getLiveCollection, getEntry, getLiveEntry, getEntries, reference, render} from 'astro:content';defineCollection()
Sección titulada “defineCollection()”Type: (input: CollectionConfig) => CollectionConfig
astro@2.0.0
Una utilidad para configurar una colección en un archivo src/content.config.*.
import { defineCollection } from 'astro:content';import { z } from 'astro/zod';import { glob } from 'astro/loaders';
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: z.object({ title: z.string(), permalink: z.string().optional(), }),});
// Expose your defined collection to Astro// with the `collections` exportexport const collections = { blog };Esta función acepta las siguientes propiedades:
Tipo: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader
astro@5.0.0
Un objeto o una función que te permite cargar datos desde cualquier fuente, local o remota, hacia una colección de contenido en tiempo de build. (Para colecciones live, ver la propiedad loader live.)
Type: ZodType | (context: SchemaContext) => ZodType
astro@2.0.0
Un objeto Zod opcional o una función que devuelve un objeto Zod para configurar el tipo y la estructura del frontmatter de los documentos de una colección. Cada valor debe usar un validador Zod. (Para colecciones live, ver la propiedad schema live.)
defineLiveCollection()
Sección titulada “defineLiveCollection()”Type: (config: LiveCollectionConfig) => LiveCollectionConfig
astro@6.0.0
Una utilidad para configurar una colección live en un archivo src/live.config.*.
import { defineLiveCollection } from 'astro:content';import { storeLoader } from '@example/astro-loader';
const products = defineLiveCollection({ loader: storeLoader({ apiKey: process.env.STORE_API_KEY, endpoint: 'https://api.example.com/v1', }),});
// Expose your defined collection to Astro// with the `collections` exportexport const collections = { products };Esta función acepta las siguientes propiedades:
Type: LiveLoader
astro@6.0.0
Un objeto que te permite cargar datos en runtime desde una fuente remota hacia una colección de contenido live. (Para colecciones en tiempo de build, ver la propiedad loader en tiempo de build.)
Type: ZodType
astro@6.0.0
Un objeto Zod opcional para configurar el tipo y la estructura de tus datos para una colección live. Cada valor debe usar un validador Zod. (Para colecciones en tiempo de build, ver la propiedad schema en tiempo de build.)
Cuando defines un schema, este tendrá precedencia sobre los tipos del live loader al consultar la colección.
reference()
Sección titulada “reference()”Tipo: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>
astro@2.5.0
Una función usada en la configuración de contenido para definir una relación, o "referencia", de una colección a otra. Esto acepta un nombre de colección y transforma la referencia en un objeto que contiene el nombre de la colección y el id de la referencia.
Este ejemplo define referencias desde un autor del blog a la colección authors y un array de posts relacionados a la misma colección blog:
import { defineCollection, reference } from 'astro:content';import { z } from 'astro/zod';import { glob, file } from 'astro/loaders';
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: z.object({ // Reference a single author from the `authors` collection by `id` author: reference('authors'), // Reference an array of related posts from the `blog` collection by `slug` relatedPosts: z.array(reference('blog')), })});
const authors = defineCollection({ loader: file("src/data/authors.json"), schema: z.object({ /* ... */ })});
export const collections = { blog, authors };La validación de las entradas referenciadas ocurre en runtime al usar getEntry() o getEntries():
// if a referenced entry is invalid, this will return undefined.const relatedPosts = await getEntries(blogPost.data.relatedPosts);getCollection()
Sección titulada “getCollection()”Tipo: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]
astro@2.0.0
Una función que recupera una lista de entradas de colecciones de contenido por nombre de colección.
Devuelve todos los elementos de la colección por defecto, y acepta una función filter opcional para filtrar por propiedades de la entrada. Esto te permite consultar solo algunos elementos de una colección basándose en el id o valores de frontmatter a través del objeto data.
---import { getCollection } from 'astro:content';
// Get all `src/data/blog/` entriesconst allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatterconst draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});---getLiveCollection()
Sección titulada “getLiveCollection()”Tipo: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>
astro@6.0.0
Una función que recupera una lista de entradas de colecciones de contenido live por nombre de colección.
Devuelve todos los elementos de la colección por defecto, y acepta un objeto filter opcional cuya estructura es definida por el loader de la colección. Esto te permite consultar solo algunos elementos de una colección o recuperar datos en una forma diferente, dependiendo de las capacidades de tu API.
---import { getLiveCollection } from 'astro:content';
// Get all `products` entries from your APIconst { entries: allProducts } = await getLiveCollection('products');
// Only return `products` that should be featuredconst { entries: featuredProducts } = await getLiveCollection('products', { featured: true });---getEntry()
Sección titulada “getEntry()”Types:
(collection: CollectionKey, id: string) => Promise<CollectionEntry | undefined>({ collection: CollectionKey, id: string }) => Promise<CollectionEntry | undefined>
astro@2.5.0
Una función que recupera una sola entrada de colección por nombre de colección y el id de la entrada. getEntry() también puede usarse para obtener entradas referenciadas y acceder a las propiedades data o body:
---import { getEntry } from 'astro:content';
// Get `src/content/blog/enterprise.md`const enterprisePost = await getEntry('blog', 'enterprise');
// Get `src/content/captains/picard.json`const picardProfile = await getEntry('captains', 'picard');
// Get the profile referenced by `data.captain`const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);---getLiveEntry()
Sección titulada “getLiveEntry()”Tipo: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>
astro@6.0.0
Una función que recupera una sola entrada de colección live por nombre de colección y un filtro opcional, ya sea como un string de id o como un objeto con seguridad de tipos.
---import { getLiveEntry } from 'astro:content';
const { entry: liveCollectionsPost } = await getLiveEntry('blog', Astro.params.id);const { entry: mattDraft } = await getLiveEntry('blog', { status: 'draft', author: 'matt',});---getEntries()
Sección titulada “getEntries()”Type: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]
astro@2.5.0
Una función que recupera múltiples entradas de colección de la misma colección. Esto es útil para devolver un array de entradas referenciadas y acceder a sus propiedades data y body asociadas.
---import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// Get related posts referenced by `data.relatedPosts`const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);---render()
Sección titulada “render()”Type: (entry: CollectionEntry) => Promise<RenderResult>
astro@5.0.0
Una función para compilar una entrada dada para renderizar. Esto devuelve las siguientes propiedades:
<Content />- Un componente usado para renderizar el contenido del documento en un archivo de Astro.headings- Una lista generada de encabezados, reflejando la utilidadgetHeadings()de Astro en importaciones de Markdown y MDX.remarkPluginFrontmatter- El objeto frontmatter modificado después de que se hayan aplicado plugins de Markdown. Establecido al tipoany.
---import { getEntry, render } from 'astro:content';const entry = await getEntry('blog', 'entry-1');
if (!entry) { // Handle Error, for example: throw new Error('Could not find blog post 1');}const { Content, headings, remarkPluginFrontmatter } = await render(entry);---Tipos de astro:content
Sección titulada “Tipos de astro:content”import type { CollectionEntry, CollectionKey, SchemaContext,} from 'astro:content';CollectionEntry
Sección titulada “CollectionEntry”Las funciones de consulta incluyendo getCollection(), getEntry() y getEntries() devuelven cada una entradas con el tipo CollectionEntry. Este tipo está disponible como utilidad desde astro:content:
import type { CollectionEntry } from 'astro:content';Un tipo genérico para usar con el nombre de la colección que estás consultando para representar una sola entrada en esa colección.
Por ejemplo, una entrada en tu colección blog tendría el tipo CollectionEntry<'blog'>.
Cada CollectionEntry es un objeto con los siguientes valores:
CollectionEntry.id
Sección titulada “CollectionEntry.id”Type: string
Un ID único. Ten en cuenta que todos los IDs del loader glob() integrado de Astro son slugificados.
CollectionEntry.collection
Sección titulada “CollectionEntry.collection”Type: CollectionKey
El nombre de una colección en la que se encuentran las entradas. Este es el nombre usado para referenciar la colección en tu schema y en las funciones de consulta.
CollectionEntry.data
Sección titulada “CollectionEntry.data”Type: CollectionSchema<TCollectionName>
Un objeto de propiedades de frontmatter inferidas de tu schema de colección (ver referencia de defineCollection()). Por defecto es any si no se configura ningún schema.
CollectionEntry.body
Sección titulada “CollectionEntry.body”Type: string | undefined
Un string que contiene el cuerpo sin compilar del documento Markdown o MDX.
Ten en cuenta que si retainBody está establecido en false, este valor será undefined en lugar de contener el contenido raw del archivo.
CollectionEntry.rendered
Sección titulada “CollectionEntry.rendered”Type: RenderedContent | undefined
El contenido renderizado de una entrada tal como lo almacena tu loader. Por ejemplo, puede ser el contenido renderizado de una entrada Markdown, o HTML de un CMS.
CollectionEntry.filePath
Sección titulada “CollectionEntry.filePath”Type: string | undefined
La ruta a una entrada relativa al directorio de tu proyecto. Este valor solo está disponible para entradas locales.
CollectionKey
Sección titulada “CollectionKey”Example Type: 'blog' | 'authors' | ...
astro@3.1.0
Una unión de strings de todos los nombres de colecciones definidos en tu archivo src/content.config.*. Este tipo puede ser útil al definir una función genérica que envuelva el getCollection() integrado.
import { type CollectionKey, getCollection } from 'astro:content';
export async function queryCollection(collection: CollectionKey) { return getCollection(collection, ({ data }) => { return data.draft !== true; });}SchemaContext
Sección titulada “SchemaContext”El objeto context que defineCollection usa para la forma de función de schema. Este tipo puede ser útil al construir schemas reutilizables para múltiples colecciones.
Esto incluye la siguiente propiedad:
image- El helper de schemaimage()que te permite usar imágenes locales en Colecciones de Contenido
import { defineCollection, type SchemaContext } from "astro:content";import { z } from 'astro/zod';import { glob } from 'astro/loaders';
export const imageSchema = ({ image }: SchemaContext) => z.object({ image: image(), description: z.string().optional(), });
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: ({ image }) => z.object({ title: z.string(), permalink: z.string().optional(), image: imageSchema({ image }) }),});Tipos de astro
Sección titulada “Tipos de astro”import type { LiveDataCollectionResult, LiveDataEntryResult,} from "astro";LiveDataCollectionResult
Sección titulada “LiveDataCollectionResult”Tipo: { entries?: Array<LiveDataEntry<TData>>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }
astro@6.0.0
Un objeto devuelto por getLiveCollection() que contiene los datos obtenidos por el live loader. Tiene las siguientes propiedades:
LiveDataCollectionResult.entries
Sección titulada “LiveDataCollectionResult.entries”Type: Array<LiveDataEntry<TData>> | undefined
Un array de objetos LiveDataEntry devueltos por el loader.
El siguiente ejemplo accede a las entradas devueltas para una colección live llamada products:
---import { getLiveCollection } from 'astro:content';
const { entries: allProducts } = await getLiveCollection('products');---LiveDataCollectionResult.error
Sección titulada “LiveDataCollectionResult.error”Type: TError | LiveCollectionError | undefined
Un error devuelto cuando el loader falló al cargar la colección. Puede ser un error personalizado definido por el loader o un error integrado.
El siguiente ejemplo accede al error devuelto al recuperar datos de una colección live llamada products:
---import { getLiveCollection } from 'astro:content';
const { error } = await getLiveCollection('products');---LiveDataCollectionResult.cacheHint
Sección titulada “LiveDataCollectionResult.cacheHint”Type: CacheHint | undefined
Un objeto que proporciona guía sobre cómo cachear esta colección.
Si has configurado un proveedor de caché, pasa el cache hint directamente a Astro.cache.set():
---import { getLiveCollection } from 'astro:content';export const prerender = false; // Not needed in 'server' mode
const { cacheHint } = await getLiveCollection('products');
if (cacheHint) { Astro.cache.set(cacheHint);}Astro.cache.set({ maxAge: 600 });---También puedes usar cache hints para establecer headers de respuesta manualmente:
---import { getLiveCollection } from 'astro:content';
const { cacheHint } = await getLiveCollection('products');
if (cacheHint?.tags) { Astro.response.headers.set('Cache-Tag', cacheHint.tags.join(','));}if (cacheHint?.lastModified) { Astro.response.headers.set('Last-Modified', cacheHint.lastModified.toUTCString());}---LiveDataEntryResult
Sección titulada “LiveDataEntryResult”Type: { entry?: LiveDataEntry<TData>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }
astro@6.0.0
Un objeto devuelto por getLiveEntry() que contiene los datos obtenidos por el live loader. Tiene las siguientes propiedades:
LiveDataEntryResult.entry
Sección titulada “LiveDataEntryResult.entry”Type: LiveDataEntry<TData> | undefined
El objeto LiveDataEntry devuelto por el loader.
El siguiente ejemplo accede a la entrada solicitada en una colección live llamada products:
---import { getLiveEntry } from 'astro:content';
const { entry } = await getLiveEntry('products', Astro.params.id);---LiveDataEntryResult.error
Sección titulada “LiveDataEntryResult.error”Type: TError | LiveCollectionError | undefined
Un error devuelto cuando el loader falló al cargar la entrada. Puede ser un error personalizado definido por el loader o un error integrado.
El siguiente ejemplo accede a la entrada solicitada en una colección live llamada products y a cualquier error, y redirige a la página 404 si existe un error:
---import { getLiveEntry } from 'astro:content';
const { entry, error } = await getLiveEntry('products', Astro.params.id);
if (error) { return Astro.redirect('/404');}---<h1>{entry.data.name}</h1>LiveDataEntryResult.cacheHint
Sección titulada “LiveDataEntryResult.cacheHint”Type: CacheHint | undefined
Un objeto que proporciona datos que pueden usarse para informar una estrategia de caché.
Si has configurado un proveedor de caché, pasa el cache hint directamente a Astro.cache.set():
---import { getLiveEntry } from 'astro:content';
export const prerender = false; // Not needed in 'server' mode
const { cacheHint } = await getLiveEntry('products', Astro.params.id);
if (cacheHint) { Astro.cache.set(cacheHint);}Astro.cache.set({ maxAge: 300 });---También puedes usar cache hints para establecer headers de respuesta manualmente:
---import { getLiveEntry } from 'astro:content';
const { cacheHint } = await getLiveEntry('products', Astro.params.id);
if (cacheHint?.tags) { Astro.response.headers.set('Cache-Tag', cacheHint.tags.join(','));}if (cacheHint?.lastModified) { Astro.response.headers.set('Last-Modified', cacheHint.lastModified.toUTCString());}---