Skip to content

Astro DB 사용 가이드

Astro DB 사용

더미로 사용될 데이터는 Astro DB를 통해 관리합니다. 직접 insert, update는 사용하지 않으며 seed를 통해서만 데이터를 관리합니다. 데이터 관리는 db/seed.js 파일을 통해 이루어집니다.

시드 업데이트

데이터를 업데이트하려면 다음 명령어를 실행합니다:

Terminal window
npm run db:seed

이 명령어는 db/seed.js에 정의된 데이터를 데이터베이스에 추가합니다.

데이터 조회 방법

Astro DB에서 데이터를 조회하는 다양한 방법을 안내합니다.

기본 조회

ComponentName.astro
---
import { Product, db } from "astro:db";
// 모든 상품 조회
const allProduct = await db.select().from(Product);
---

필터링 조회

특정 조건으로 데이터를 필터링하는 방법:

ComponentName.astro
---
import { Product, db, eq } from "astro:db";
// 브랜드가 'STUDIO TOMBOY'인 상품만 조회
const filteredItems = await db
.select()
.from(Product)
.where(eq(Product.brand, "STUDIO TOMBOY"));
---

복합 조건 필터링

andor 조건을 사용하여 복합 필터링:

ComponentName.astro
---
import { Product, db, eq, and, or } from "astro:db";
// OR 조건: 두 브랜드 중 하나라도 일치하는 상품 조회
const multipleItems = await db
.select()
.from(Product)
.where(
or(eq(Product.brand, "STUDIO TOMBOY"), eq(Product.brand, "TOMMY HILFIGER")),
);
// AND 조건: 두 조건을 모두 만족하는 상품 조회
const combinedItems = await db
.select()
.from(Product)
.where(
and(
eq(Product.brand, "STUDIO TOMBOY"),
eq(Product.name, "레더 블루종 자켓"),
),
);
---

패턴 매칭 (LIKE)

텍스트 필드에 패턴 매칭 적용:

ComponentName.astro
---
import { Product, db, like } from "astro:db";
// 가격이 3으로 시작하는 상품 조회
const priceRangeItems = await db
.select()
.from(Product)
.where(like(Product.price, "3%"));
// 이름에 '자켓'이 포함된 상품 조회
const jacketItems = await db
.select()
.from(Product)
.where(like(Product.name, "%자켓%"));
---

결과 제한

조회 결과 수 제한:

ComponentName.astro
---
import { Product, db } from "astro:db";
// 최대 10개 상품만 조회
const limitedItems = await db.select().from(Product).limit(10);
---

Astro 컴포넌트에서 데이터 사용하기

ComponentName.astro
---
// src/pages/index.astro
import { Product, db, eq } from "astro:db";
import Layout from "@mw/layouts/Layout.astro";
// 빌드 타임에 데이터 조회
const products = await db
.select()
.from(Product)
.where(eq(Product.brand, "STUDIO TOMBOY"));
---
<Layout title="상품 목록">
<main>
<h1>STUDIO TOMBOY 상품</h1>
<div class="product-grid">
{
products.map((product) => (
<div class="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.brand}</h3>
<p class="product-name">{product.name}</p>
<p class="product-price">
{product.discount ? (
<>
<span class="original-price">{product.price}</span>{" "}
<span class="discount-price">{product.discount}</span>
</>
) : (
<span>{product.price}</span>
)}
</p>
<a href={product.link} class="view-button">
상품 보기
</a>
</div>
))
}
</div>
</main>
</Layout>