Strapi & Astro
Strapi는 사용자 정의가 가능한 오픈 소스 헤드리스 CMS입니다.
Astro와 통합
섹션 제목: “Astro와 통합”이 가이드에서는 Strapi와 Astro를 연결하는 래퍼 함수를 구축합니다.
전제조건
섹션 제목: “전제조건”시작하려면 다음이 필요합니다.
- Astro 프로젝트 - 아직 Astro 프로젝트가 없다면 설치 가이드를 참조하여 즉시 설치하고 실행할 수 있습니다.
- Strapi CMS 서버 - 로컬 환경에 Strapi 서버를 설정할 수 있습니다.
.env에 Strapi URL 추가
섹션 제목: “.env에 Strapi URL 추가”Astro에 Strapi URL을 추가하려면 프로젝트 루트에 .env 파일을 만들고 (아직 없는 경우) 다음 변수를 추가하세요.
STRAPI_URL="http://127.0.0.1:1337" # 또는 여려분의 IP 주소를 사용하세요.Astro 프로젝트에서 이 환경 변수를 사용하려면 개발 서버를 다시 시작하세요.
환경 변수에 IntelliSense를 사용하려면 src/ 디렉터리에 env.d.ts 파일을 만들고 다음과 같이 ImportMetaEnv를 구성하면 됩니다.
interface ImportMetaEnv { readonly STRAPI_URL: string;}이제 루트 디렉터리에 새 파일이 포함되어야 합니다.
디렉터리src/
- env.d.ts
- .env
- astro.config.mjs
- package.json
.env 파일에 대해 자세히 알아보세요.
API 래퍼 만들기
섹션 제목: “API 래퍼 만들기”src/lib/strapi.ts에 새 파일을 만들고 다음 래퍼 함수를 추가하여 Strapi API와 상호 작용합니다.
interface Props { endpoint: string; query?: Record<string, string>; wrappedByKey?: string; wrappedByList?: boolean;}
/** * Fetches data from the Strapi API * @param endpoint - The endpoint to fetch from * @param query - The query parameters to add to the url * @param wrappedByKey - The key to unwrap the response from * @param wrappedByList - If the response is a list, unwrap it * @returns */export default async function fetchApi<T>({ endpoint, query, wrappedByKey, wrappedByList,}: Props): Promise<T> { if (endpoint.startsWith('/')) { endpoint = endpoint.slice(1); }
const url = new URL(`${import.meta.env.STRAPI_URL}/api/${endpoint}`);
if (query) { Object.entries(query).forEach(([key, value]) => { url.searchParams.append(key, value); }); } const res = await fetch(url.toString()); let data = await res.json();
if (wrappedByKey) { data = data[wrappedByKey]; }
if (wrappedByList) { data = data[0]; }
return data as T;}이 함수에는 다음 속성을 가진 객체가 필요합니다.
endpoint- 가져올 엔포인트입니다.query- URL 끝에 추가할 쿼리 매개변수입니다.wrappedByKey-Response를 래핑하는 객체의data키입니다.wrappedByList- Strapi에서 반환된 목록을 “해제”하고 첫 번째 항목만 반환하는 매개변수입니다.
선택 사항: Article 인터페이스 생성
섹션 제목: “선택 사항: Article 인터페이스 생성”TypeScript를 사용하는 경우 src/interfaces/article.ts에서 Strapi 콘텐츠 타입에 해당하는 다음 Article 인터페이스를 만듭니다.
export default interface Article { documentId: number; title: string; description: string; content: string; slug: string; createdAt: string; updatedAt: string; publishedAt: string;}자신의 프로젝트 데이터에 맞게 이 인터페이스를 수정하거나 여러 인터페이스를 생성할 수 있습니다.
디렉터리src/
디렉터리interfaces/
- article.ts
디렉터리lib/
- strapi.ts
- env.d.ts
- .env
- astro.config.mjs
- package.json
아티클 목록 표시
섹션 제목: “아티클 목록 표시”-
홈페이지
src/pages/index.astro를 업데이트하여 블로그 게시물 목록을 표시하세요. 각 게시물에는 설명과 해당 페이지에 대한 링크가 포함되어 있습니다. -
래퍼 함수와 인터페이스를 가져옵니다. 아티클을 가져와 목록을 반환하려면 다음 API 호출을 추가하세요.
src/pages/index.astro ---import fetchApi from '../lib/strapi';import type Article from '../interfaces/article';const articles = await fetchApi<Article[]>({endpoint: 'articles', // 가져올 콘텐츠 타입wrappedByKey: 'data', // 응답을 해제할 key});---API 호출은
http://localhost:1337/api/articles에서 데이터를 요청하고articles(데이터를 나타내는 json 객체 배열)를 반환합니다.[{documentId: 1,title: "What's inside a Black Hole",description: "Maybe the answer is in this article, or not...",content: "Well, we don't know yet...",slug: "what-s-inside-a-black-hole",createdAt: "2023-05-28T13:19:46.421Z",updatedAt: "2023-05-28T13:19:46.421Z",publishedAt: "2023-05-28T13:19:45.826Z"},// ...] -
API에서 반환된
articles배열의 데이터를 사용하여 Strapi 블로그 게시물을 목록에 표시합니다. 이러한 게시물은 다음 단계에서 생성할 개별 페이지로 연결됩니다.src/pages/index.astro ---import fetchApi from '../lib/strapi';import type Article from '../interfaces/article';const articles = await fetchApi<Article[]>({endpoint: 'articles?populate=image',wrappedByKey: 'data',});---<!DOCTYPE html><html lang="en"><head><title>Strapi & Astro</title></head><body><main><ul>{articles.map((article) => (<li><a href={`/blog/${article.slug}/`}>{article.title}</a></li>))}</ul></main></body></html>