콘텐츠로 이동

콘텐츠 컬렉션 API 참조

추가된 버전: astro@2.0.0

빌드 타임 콘텐츠 컬렉션은 로컬 Markdown, MDX, Markdoc, YAML, TOML, JSON 파일 및 원격 콘텐츠를 구성, 쿼리 및 렌더링할 수 있는 API를 제공합니다.

추가된 버전: astro@6.0.0 새로운 기능

라이브 콘텐츠 컬렉션은 원격 소스로부터 최신의 라이브 데이터를 구성, 쿼리 및 렌더링할 수 있는 API를 제공합니다.

기능 및 사용 예시는 콘텐츠 컬렉션 가이드를 참조하세요.

import {
defineCollection,
defineLiveCollection,
getCollection,
getLiveCollection,
getEntry,
getLiveEntry,
getEntries,
reference,
render
} from 'astro:content';

타입: (input: CollectionConfig) => CollectionConfig

추가된 버전: astro@2.0.0

src/content.config.* 파일에서 컬렉션을 구성하기 위한 유틸리티입니다.

src/content.config.ts
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(),
}),
});
// `collections` 내보내기를 통해 정의된 컬렉션을 Astro에 노출합니다.
export const collections = { blog };

이 함수는 다음 속성을 허용합니다:

타입: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader

추가된 버전: astro@5.0.0

로컬 또는 원격 등 모든 소스에서 빌드 타임 콘텐츠 컬렉션으로 데이터를 로드할 수 있게 해주는 객체 또는 함수입니다. (라이브 컬렉션의 경우, 라이브 loader 속성을 참조하세요.)

가이드 설명 및 사용 예시를 통해 빌드 타임 컬렉션 로더에 대해 알아보세요.

타입: ZodType | (context: SchemaContext) => ZodType

추가된 버전: astro@2.0.0

컬렉션에 대한 문서 프론트매터의 타입과 형태를 구성하기 위해 Zod 객체를 반환하는 선택적 Zod 객체 또는 함수입니다. 각 값은 Zod 유효성 검사기를 사용해야 합니다. (라이브 컬렉션의 경우, 라이브 schema 속성을 참조하세요.)

가이드 설명, 사용 예시 및 공통 데이터 타입을 통해 Zod를 사용한 컬렉션 스키마를 정의하는 방법에 대해 알아보세요.

타입: (config: LiveCollectionConfig) => LiveCollectionConfig

추가된 버전: astro@6.0.0 새로운 기능

src/live.config.* 파일에서 라이브 컬렉션을 구성하기 위한 유틸리티입니다.

src/live.config.ts
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',
}),
});
// `collections` 내보내기를 통해 정의된 컬렉션을 Astro에 노출합니다.
export const collections = { products };

이 함수는 다음 속성을 허용합니다:

타입: LiveLoader

추가된 버전: astro@6.0.0 새로운 기능

런타임에 원격 소스에서 라이브 콘텐츠 컬렉션으로 데이터를 로드할 수 있게 해주는 객체입니다. (빌드 타임 컬렉션의 경우, 빌드 타임 loader 속성을 참조하세요.)

가이드 설명 및 사용 예시를 통해 라이브 로더를 생성하는 방법에 대해 알아보세요.

타입: ZodType

추가된 버전: astro@6.0.0 새로운 기능

라이브 컬렉션에 대한 데이터의 타입과 형태를 구성하기 위한 선택적 Zod 객체입니다. 각 값은 Zod 유효성 검사기를 사용해야 합니다. (빌드 타임 컬렉션의 경우, 빌드 타임 schema 속성을 참조하세요.)

스키마를 정의하면 컬렉션을 쿼리할 때 라이브 로더의 타입보다 우선 적용됩니다.

가이드 설명 및 사용 예시를 통해 라이브 컬렉션에서 Zod 스키마 사용하는 방법에 대해 알아보세요.

타입: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>

추가된 버전: astro@2.5.0

콘텐츠 구성에서 한 컬렉션과 다른 컬렉션 간의 관계 또는 “참조”를 정의하는 데 사용되는 함수입니다. 컬렉션 이름을 인자로 받아 참조를 컬렉션 이름과 참조 ID를 포함하는 객체로 변환합니다.

이 예시는 블로그 작성자를 authors 컬렉션으로 참조하고, 관련 게시물 배열을 동일한 blog 컬렉션으로 참조하도록 정의합니다:

src/content.config.ts
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({
// `id`를 통해 `authors` 컬렉션에서 단일 작성자를 참조합니다.
author: reference('authors'),
// `slug`를 통해 `blog` 컬렉션에서 관련 게시물 배열을 참조합니다.
relatedPosts: z.array(reference('blog')),
})
});
const authors = defineCollection({
loader: file("src/data/authors.json"),
schema: z.object({ /* ... */ })
});
export const collections = { blog, authors };

참조된 엔트리에 대한 유효성 검사는 getEntry() 또는 getEntries()를 사용할 때 런타임에 발생합니다:

src/pages/[posts].astro
// 참조된 엔트리가 유효하지 않은 경우 undefined를 반환합니다.
const relatedPosts = await getEntries(blogPost.data.relatedPosts);
가이드 설명 및 사용 예시를 통해 컬렉션 참조 정의 및 사용 방법에 대해 알아보세요.

타입: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]

추가된 버전: astro@2.0.0

컬렉션 이름으로 콘텐츠 컬렉션 엔트리 목록을 검색하는 함수입니다.

기본적으로 컬렉션의 모든 항목을 반환하며, 엔트리 속성에 따라 범위를 좁히기 위한 선택적 filter 함수를 허용합니다. 이를 통해 iddata 객체를 통한 프론트매터 값을 기반으로 컬렉션의 일부 항목만 쿼리할 수 있습니다.

src/pages/blog/index.astro
---
import { getCollection } from 'astro:content';
// 모든 `src/data/blog/` 엔트리를 가져옵니다.
const allBlogPosts = await getCollection('blog');
// 프론트매터에 `draft: true`가 있는 게시물만 반환합니다.
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---
가이드 설명 및 사용 예시를 통한 빌드 타임 컬렉션 쿼리 방법에 대해 알아보세요.

타입: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>

추가된 버전: astro@6.0.0 새로운 기능

컬렉션 이름으로 라이브 콘텐츠 컬렉션 엔트리 목록을 검색하는 함수입니다.

기본적으로 컬렉션의 모든 항목을 반환하며, 컬렉션의 로더에 의해 형태가 정의되는 선택적 filter 객체를 허용합니다. 이를 통해 API 기능에 따라 컬렉션의 일부 항목만 쿼리하거나 다른 형태의 데이터를 검색할 수 있습니다.

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
// API에서 모든 `products` 엔트리를 가져옵니다.
const { entries: allProducts } = await getLiveCollection('products');
// 추천 상품인 `products`만 반환합니다.
const { entries: featuredProducts } = await getLiveCollection('products', { featured: true });
---
가이드 설명 및 사용 예시를 통해 라이브 컬렉션 데이터 액세스 방법에 대해 알아보세요.

타입:

추가된 버전: astro@2.5.0

컬렉션 이름과 엔트리 id를 통해 단일 컬렉션 엔트리를 검색하는 함수입니다. getEntry()data 또는 body 속성에 액세스하기 위해 참조된 엔트리를 가져오는 데에도 사용될 수 있습니다:

src/pages/index.astro
---
import { getEntry } from 'astro:content';
// `src/content/blog/enterprise.md`를 가져옵니다.
const enterprisePost = await getEntry('blog', 'enterprise');
// `src/content/captains/picard.json`을 가져옵니다.
const picardProfile = await getEntry('captains', 'picard');
// `data.captain`에 의해 참조된 프로필을 가져옵니다.
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---
가이드 설명 및 사용 예시를 통해 빌드 타임 컬렉션 쿼리 방법에 대해 자세히 알아보세요.

타입: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>

추가된 버전: astro@6.0.0 새로운 기능

컬렉션 이름과 선택적 필터(id 문자열 또는 타입 안정성이 보장된 객체)를 통해 단일 라이브 컬렉션 엔트리를 검색하는 함수입니다.

src/pages/blog/[id].astro
---
import { getLiveEntry } from 'astro:content';
const { entry: liveCollectionsPost } = await getLiveEntry('blog', Astro.params.id);
const { entry: mattDraft } = await getLiveEntry('blog', {
status: 'draft',
author: 'matt',
});
---
가이드 설명 및 사용 예시를 통해 라이브 컬렉션 데이터에 액세스하는 방법에 대해 알아보세요.

타입: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]

추가된 버전: astro@2.5.0

동일한 컬렉션에서 여러 컬렉션 엔트리를 검색하는 함수입니다. 이는 참조된 엔트리 배열을 반환하여 관련 databody 속성에 액세스하는 데 유용합니다.

src/pages/blog/enterprise/index.astro
---
import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// `data.relatedPosts`에 의해 참조된 관련 게시물을 가져옵니다.
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

타입: (entry: CollectionEntry) => Promise<RenderResult>

추가된 버전: astro@5.0.0

렌더링을 위해 주어진 엔트리를 컴파일하는 함수입니다. 이 함수는 다음 속성들을 반환합니다:

src/pages/blog/entry-1.astro
---
import { getEntry, render } from 'astro:content';
const entry = await getEntry('blog', 'entry-1');
if (!entry) {
// 예를 들어 다음과 같이 에러를 처리합니다:
throw new Error('Could not find blog post 1');
}
const { Content, headings, remarkPluginFrontmatter } = await render(entry);
---
가이드 설명 및 사용 예시를 통해 엔트리 본문 콘텐츠를 렌더링하는 방법에 대해 알아보세요.
import type {
CollectionEntry,
CollectionKey,
SchemaContext,
} from 'astro:content';

getCollection(), getEntry(), getEntries()를 포함한 쿼리 함수들은 각각 CollectionEntry 타입의 엔트리를 반환합니다. 이 타입은 astro:content에서 유틸리티로 사용할 수 있습니다:

import type { CollectionEntry } from 'astro:content';

쿼리 중인 컬렉션의 이름과 함께 사용하여 해당 컬렉션의 단일 엔트리를 나타내는 제네릭 타입입니다. 예를 들어, blog 컬렉션의 엔트리는 CollectionEntry<'blog'> 타입을 갖게 됩니다.

CollectionEntry는 다음 값을 포함하는 객체입니다:

타입: string

고유 ID입니다. Astro의 내장 glob() 로더를 통한 모든 ID는 슬러그화됩니다.

타입: CollectionKey

엔트리가 위치한 컬렉션의 이름입니다. 이는 스키마 및 쿼리 함수에서 컬렉션을 참조하는 데 사용되는 이름입니다.

타입: CollectionSchema<TCollectionName>

컬렉션 스키마에서 추론된 프론트매터 속성 객체입니다 (defineCollection() 참조). 스키마가 구성되지 않은 경우 기본값은 any입니다.

타입: string | undefined

Markdown 또는 MDX 문서의 컴파일되지 않은 원본 본문을 포함하는 문자열입니다.

retainBodyfalse로 설정된 경우, 이 값은 원본 파일 내용 대신 undefined가 됩니다.

타입: RenderedContent | undefined

로더에 의해 저장된 엔트리의 렌더링된 콘텐츠입니다. 예를 들어, Markdown 엔트리의 렌더링된 내용이나 CMS의 HTML일 수 있습니다.

타입: string | undefined

프로젝트 디렉토리에 대한 엔트리의 상대 경로입니다. 이 값은 로컬 엔트리에 대해서만 사용할 수 있습니다.

예시 타입: 'blog' | 'authors' | ...

추가된 버전: astro@3.1.0

src/content.config.* 파일에 정의된 모든 컬렉션 이름의 문자열 유니온입니다. 이 타입은 내장 getCollection()을 래핑하는 제네릭 함수를 정의할 때 유용할 수 있습니다.

src/utils/collections.ts
import { type CollectionKey, getCollection } from 'astro:content';
export async function queryCollection(collection: CollectionKey) {
return getCollection(collection, ({ data }) => {
return data.draft !== true;
});
}

defineCollectionschema 함수의 인자로 사용하는 context 객체입니다. 이 타입은 여러 컬렉션에서 재사용 가능한 스키마를 빌드할 때 유용할 수 있습니다.

이 객체는 다음 속성을 포함합니다:

src/content.config.ts
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 })
}),
});
import type {
LiveDataCollectionResult,
LiveDataEntryResult,
} from "astro";

타입: { entries?: Array<LiveDataEntry<TData>>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }

추가된 버전: astro@6.0.0 새로운 기능

getLiveCollection()에 의해 반환되는 객체로, 라이브 로더에서 가져온 데이터를 포함합니다. 다음 속성들을 갖습니다:

타입: Array<LiveDataEntry<TData>> | undefined

로더에 의해 반환된 LiveDataEntry 객체들의 배열입니다.

다음 예시는 products라는 이름의 라이브 컬렉션에 대해 반환된 엔트리에 액세스합니다:

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
const { entries: allProducts } = await getLiveCollection('products');
---
가이드 설명 및 사용 예시를 통해 라이브 데이터 액세스 방법에 대해 알아보세요.

타입: TError | LiveCollectionError | undefined

로더가 컬렉션을 로드하는 데 실패했을 때 반환되는 에러입니다. 로더에서 정의한 커스텀 에러이거나 내장 에러일 수 있습니다.

다음 예시는 products라는 이름의 라이브 컬렉션에서 데이터를 검색할 때 반환된 에러에 액세스합니다:

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
const { error } = await getLiveCollection('products');
---
가이드 설명 및 사용 예시를 통해 에러 처리 방법에 대해 자세히 알아보세요.

타입: CacheHint | undefined

이 컬렉션을 캐시하는 방법에 대한 지침을 제공하는 객체입니다.

실험적 라우트 캐싱 (EN)이 활성화된 경우, 캐시 힌트를 Astro.cache.set()에 직접 전달하세요:

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
export const prerender = false; // 'server' 모드에서는 필요하지 않습니다.
const { cacheHint } = await getLiveCollection('products');
if (cacheHint) {
Astro.cache.set(cacheHint);
}
Astro.cache.set({ maxAge: 600 });
---

캐시 힌트를 사용하여 응답 헤더를 수동으로 설정할 수도 있습니다:

src/pages/shop/index.astro
---
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());
}
---

타입: { entry?: LiveDataEntry<TData>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }

추가된 버전: astro@6.0.0 새로운 기능

getLiveEntry()에 의해 반환되는 객체로, 라이브 로더에서 가져온 데이터를 포함합니다. 다음 속성들을 갖습니다:

타입: LiveDataEntry<TData> | undefined

로더에 의해 반환된 LiveDataEntry 객체입니다.

다음 예시는 products라는 이름의 라이브 컬렉션에서 요청된 엔트리에 액세스합니다:

src/pages/shop/[id].astro
---
import { getLiveEntry } from 'astro:content';
const { entry } = await getLiveEntry('products', Astro.params.id);
---
가이드 설명 및 사용 예시를 통해 라이브 데이터 액세스 방법에 대해 알아보세요.

타입: TError | LiveCollectionError | undefined

로더가 엔트리를 로드하는 데 실패했을 때 반환되는 에러입니다. 로더에서 정의한 커스텀 에러이거나 내장 에러일 수 있습니다.

다음 예시는 products라는 이름의 라이브 컬렉션에서 요청된 엔트리와 에러에 액세스하며, 에러가 있는 경우 404 페이지로 리다이렉트합니다:

src/pages/shop/[id].astro
---
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>
가이드 설명 및 사용 예시를 통해 에러 처리 방법에 대해 자세히 알아보세요.

타입: CacheHint | undefined

캐싱 전략을 결정하는 데 사용될 수 있는 데이터를 제공하는 객체입니다.

실험적 라우트 캐싱 (EN)이 활성화된 경우, 캐시 힌트를 Astro.cache.set()에 직접 전달하세요:

src/pages/shop/[id].astro
---
import { getLiveEntry } from 'astro:content';
export const prerender = false; // 'server' 모드에서는 필요하지 않습니다.
const { cacheHint } = await getLiveEntry('products', Astro.params.id);
if (cacheHint) {
Astro.cache.set(cacheHint);
}
Astro.cache.set({ maxAge: 300 });
---

캐시 힌트를 사용하여 응답 헤더를 수동으로 설정할 수도 있습니다:

src/pages/shop/[id].astro
---
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());
}
---
기여하기 커뮤니티 후원하기