diff --git a/src/content/docs/ko/guides/actions.mdx b/src/content/docs/ko/guides/actions.mdx index 994c9e51890cb..942e99a91f28e 100644 --- a/src/content/docs/ko/guides/actions.mdx +++ b/src/content/docs/ko/guides/actions.mdx @@ -14,7 +14,7 @@ Astro 액션을 사용하면 타입 안전성을 갖춘 백엔드 함수를 정 클라이언트와 서버 코드 간의 원활한 통신을 위해 API 엔드포인트 대신 액션을 사용하세요: -- [Zod 유효성 검사](https://zod.dev/?id=primitives)를 사용하여 JSON 및 양식 데이터 입력의 유효성을 자동으로 검사하세요. +- [Zod 유효성 검사](/ko/reference/modules/astro-zod/)를 사용하여 JSON 및 양식 데이터 입력의 유효성을 자동으로 검사하세요. - 클라이언트는 물론 [HTML 양식 액션에서도](#html-양식-액션에서-액션-호출) 백엔드를 호출할 수 있는 타입이 안전한 함수를 생성하세요. 수동 `fetch()` 호출이 필요 없습니다. - [`ActionError`](/ko/reference/modules/astro-actions/#actionerror) 객체로 백엔드 오류를 표준화하세요. @@ -24,7 +24,7 @@ Astro 액션을 사용하면 타입 안전성을 갖춘 백엔드 함수를 정 ```ts title="src/actions/index.ts" import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { myAction: defineAction({ /* ... */ }) @@ -62,22 +62,22 @@ async () => { } ``` -2. `astro:actions`에서 `defineAction()` 유틸리티를, `astro:schema`에서 `z` 객체를 가져옵니다. +2. `astro:actions`에서 `defineAction()` 유틸리티를, `astro/zod`에서 `z` 객체를 가져옵니다. ```ts ins={1-2} title="src/actions/index.ts" import { defineAction } from 'astro:actions'; - import { z } from 'astro:schema'; + import { z } from 'astro/zod'; export const server = { // 액션 정의 } ``` -3. `defineAction()` 유틸리티를 사용하여 `getGreeting` 액션을 정의합니다. `input` 속성은 [Zod](https://zod.dev) 스키마로 입력 매개변수의 유효성을 검사하는 데 사용되며 `handler()` 함수에는 서버에서 실행할 백엔드 로직이 포함되어 있습니다. +3. `defineAction()` 유틸리티를 사용하여 `getGreeting` 액션을 정의합니다. `input` 속성은 [Zod 스키마](/ko/reference/modules/astro-zod/#일반적인-데이터-타입-유효성-검사기)로 입력 매개변수의 유효성을 검사하는 데 사용되며 `handler()` 함수에는 서버에서 실행할 백엔드 로직이 포함되어 있습니다. ```ts ins={5-12} title="src/actions/index.ts" import { defineAction } from 'astro:actions'; - import { z } from 'astro:schema'; + import { z } from 'astro/zod'; export const server = { getGreeting: defineAction({ @@ -213,7 +213,7 @@ const updatedLikes = await actions.likePost.orThrow({ postId: 'example' }); ```ts title="src/actions/index.ts" ins=/ActionError(?= )/ ins={9-12} import { defineAction, ActionError } from "astro:actions"; -import { z } from "astro:schema"; +import { z } from "astro/zod"; export const server = { likePost: defineAction({ @@ -290,7 +290,7 @@ export function LogoutButton() { ```ts title="src/actions/index.ts" ins={6} import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { comment: defineAction({ @@ -319,7 +319,7 @@ export const server = { ```ts title="src/actions/index.ts" {7-21} "create" "update" import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { changeUser: defineAction({ @@ -378,7 +378,7 @@ export const server = { ```ts title="src/actions/index.ts" ins={5-12} import { defineAction } from 'astro:actions'; - import { z } from 'astro:schema'; + import { z } from 'astro/zod'; export const server = { newsletter: defineAction({ @@ -492,7 +492,7 @@ import { actions } from 'astro:actions'; ```ts title="src/actions/index.ts" mark={10} import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { createProduct: defineAction({ diff --git a/src/content/docs/ko/guides/astro-db.mdx b/src/content/docs/ko/guides/astro-db.mdx index 3163dca4c0c5c..67461a9a6cfb0 100644 --- a/src/content/docs/ko/guides/astro-db.mdx +++ b/src/content/docs/ko/guides/astro-db.mdx @@ -401,7 +401,7 @@ const comments = await db.select().from(Comment); // src/actions/index.ts import { db, Comment } from 'astro:db'; import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { addComment: defineAction({ diff --git a/src/content/docs/ko/guides/backend/xata.mdx b/src/content/docs/ko/guides/backend/xata.mdx index e304bcb52b347..f49580dc423c7 100644 --- a/src/content/docs/ko/guides/backend/xata.mdx +++ b/src/content/docs/ko/guides/backend/xata.mdx @@ -12,7 +12,6 @@ i18nReady: true import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' import { FileTree } from '@astrojs/starlight/components'; - [Xata](https://xata.io)는 일관된 단일 REST API를 노출하여 관계형 데이터베이스, 검색 엔진 및 분석 엔진의 기능을 결합한 **서버리스 데이터 플랫폼**입니다. ## Xata를 사용하여 데이터베이스 추가 diff --git a/src/content/docs/ko/guides/content-collections.mdx b/src/content/docs/ko/guides/content-collections.mdx index 20e512f1a6fa8..4e4eddacae2eb 100644 --- a/src/content/docs/ko/guides/content-collections.mdx +++ b/src/content/docs/ko/guides/content-collections.mdx @@ -64,16 +64,19 @@ Astro v5.0에서는 콘텐츠 컬렉션을 정의하고 쿼리하기 위한 Cont ```ts title="src/content.config.ts" // 1. `astro:content`에서 유틸리티 가져오기 -import { defineCollection, z } from 'astro:content'; +import { defineCollection } from 'astro:content'; // 2. 로더 가져오기 import { glob, file } from 'astro/loaders'; -// 3. 컬렉션 정의 +// 3. Zod 가져오기 +import { z } from 'astro/zod'; + +// 4. 컬렉션 정의 const blog = defineCollection({ /* ... */ }); const dogs = defineCollection({ /* ... */ }); -// 4. 컬렉션을 등록하기 위해 단일 `collections` 객체 내보내기 +// 5. 컬렉션을 등록하기 위해 단일 `collections` 객체 내보내기 export const collections = { blog, dogs }; ``` @@ -89,9 +92,10 @@ Astro는 로컬 콘텐츠를 가져오기 위한 [두 가지 내장 로더 함 [`file()` 로더](/ko/reference/content-loader-reference/#file-로더)는 단일 로컬 파일에서 여러 항목을 생성합니다. 파일의 각 항목에는 고유한 `id` 키 속성이 있어야 합니다. 이 로더는 파일의 `base` 파일 경로를 인자로 받고 자동으로 분석할 수 없는 파일을 위해 선택적으로 [`parser` 함수](#parser-함수)를 인자로 받습니다. 데이터 파일을 객체 배열로 구문 분석할 수 있는 경우 이 로더를 사용합니다. -```ts title="src/content.config.ts" {5,9} -import { defineCollection, z } from 'astro:content'; +```ts title="src/content.config.ts" {6,10} +import { defineCollection } from 'astro:content'; import { glob, file } from 'astro/loaders'; // 레거시 API에서는 사용 불가능 +import { z } from 'astro/zod'; const blog = defineCollection({ loader: glob({ pattern: "**/*.md", base: "./src/data/blog" }), @@ -208,11 +212,12 @@ Astro 통합이나 Vite 플러그인을 만드는 것처럼, [로더를 NPM 패 Astro가 새 스키마 또는 업데이트된 스키마를 인식하려면 개발 서버를 다시 시작하거나 [콘텐츠 레이어 동기화](/ko/reference/cli-reference/#astro-dev) (s + enter)를 통해 `astro:content` 모듈을 정의해야 할 수도 있습니다. ::: -컬렉션 항목의 모든 프런트매터나 데이터 속성은 Zod 데이터 타입을 사용하여 정의되어야 합니다: +컬렉션 항목의 모든 프런트매터나 데이터 속성은 [Zod의 데이터 타입](/ko/reference/modules/astro-zod/#일반적인-데이터-타입-유효성-검사기)을 사용하여 정의되어야 합니다. -```ts title="src/content.config.ts" {6-11,15-19} -import { defineCollection, z } from 'astro:content'; -import { glob, file } from 'astro/loaders'; // 레거시 API에서는 사용 불가능 +```ts title="src/content.config.ts" {7-12,16-20} +import { defineCollection } from 'astro:content'; +import { glob, file } from 'astro/loaders'; +import { z } from 'astro/zod'; const blog = defineCollection({ loader: glob({ pattern: "**/*.md", base: "./src/data/blog" }), @@ -239,43 +244,13 @@ export const collections = { blog, dogs }; Astro는 콘텐츠 스키마를 위해 [Zod](https://github.com/colinhacks/zod)를 사용합니다. Astro는 Zod를 통해 컬렉션의 모든 파일의 데이터를 검증하고, 프로젝트에서 콘텐츠를 쿼리할 때 자동으로 TypeScript 타입을 제공할 수 있습니다. -Astro에서 Zod를 사용하려면 `"astro:content"`에서 `z` 유틸리티를 가져옵니다. 이는 Zod 라이브러리를 다시 내보낸 것으로, Zod의 모든 기능을 지원합니다. - -```ts -// 예시: 자주 사용되는 Zod 데이터 타입 치트 시트 -import { z, defineCollection } from 'astro:content'; - -defineCollection({ - schema: z.object({ - isDraft: z.boolean(), - title: z.string(), - sortOrder: z.number(), - image: z.object({ - src: z.string(), - alt: z.string(), - }), - author: z.string().default('Anonymous'), - language: z.enum(['en', 'es']), - tags: z.array(z.string()), - footnote: z.string().optional(), - - // YAML에서 따옴표로 감싸지 않은 날짜는 Date 객체로 해석됩니다 - publishDate: z.date(), // e.g. 2024-09-17 - - // 날짜 문자열(예: "2022-07-08")을 Date 객체로 변환 - updatedDate: z.string().transform((str) => new Date(str)), - - authorContact: z.string().email(), - canonicalURL: z.string().url(), - }) -}) -``` +Astro에서 Zod를 사용하려면 `"astro/zod"`에서 `z` 유틸리티를 가져와야 합니다. 이는 Zod 라이브러리를 다시 내보낸 것으로, Zod의 모든 기능을 지원합니다. -[Zod의 README](https://github.com/colinhacks/zod)에서 Zod의 작동 방식과 사용 가능한 기능에 대한 전체 문서를 확인하세요. +일반적인 데이터 타입 치트 시트와 Zod의 작동 방식 및 사용 가능한 기능에 대해 알아보려면 [`z` 유틸리티 참조](/ko/reference/modules/astro-zod/)를 확인하세요. ##### Zod 스키마 메서드 -모든 [Zod 스키마 메서드](https://zod.dev/?id=schema-methods)(예: `.parse()`, `.transform()`)는 일부 제한사항과 함께 사용할 수 있습니다. 특히 `image().refine()`을 사용한 이미지의 사용자 정의 유효성 검사는 지원되지 않습니다. +모든 [Zod 스키마 메서드](/ko/reference/modules/astro-zod/#zod-메서드-사용하기)(예: `.parse()`, `.transform()`)는 일부 제한사항과 함께 사용할 수 있습니다. 특히 `image().refine()`을 사용한 이미지의 사용자 정의 유효성 검사는 지원되지 않습니다. #### 컬렉션 참조 정의 @@ -286,8 +261,9 @@ Collections API의 [`reference()` 함수](/ko/reference/modules/astro-content/#r 일반적인 예시로는 JSON으로 저장된 재사용 가능한 작성자 프로필을 참조하거나, 같은 컬렉션에 저장된 관련 게시물 URL을 참조하는 블로그 게시물이 있습니다: ```ts title="src/content.config.ts" -import { defineCollection, reference, z } from 'astro:content'; +import { defineCollection, reference } from 'astro:content'; import { glob } from 'astro/loaders'; +import { z } from 'astro/zod'; const blog = defineCollection({ loader: glob({ pattern: '**/[^_]*.md', base: "./src/data/blog" }), diff --git a/src/content/docs/ko/guides/images.mdx b/src/content/docs/ko/guides/images.mdx index 1deb607658b58..a478621ed75fe 100644 --- a/src/content/docs/ko/guides/images.mdx +++ b/src/content/docs/ko/guides/images.mdx @@ -594,7 +594,8 @@ This is a blog post 콘텐츠 컬렉션 스키마의 `image` 도우미를 사용하면 이미지를 검증하고 가져올 수 있습니다. ```ts title="src/content.config.ts" -import { defineCollection, z } from "astro:content"; +import { defineCollection } from "astro:content"; +import { z } from "astro/zod"; const blogCollection = defineCollection({ schema: ({ image }) => z.object({ diff --git a/src/content/docs/ko/guides/integrations-guide/mdx.mdx b/src/content/docs/ko/guides/integrations-guide/mdx.mdx index 7f1907d335a3f..345922870e581 100644 --- a/src/content/docs/ko/guides/integrations-guide/mdx.mdx +++ b/src/content/docs/ko/guides/integrations-guide/mdx.mdx @@ -101,8 +101,9 @@ MDX 통합을 추가하면 JSX 변수, 표현식, 컴포넌트로 Markdown을 콘텐츠 컬렉션에 MDX 파일을 포함하려면, [컬렉션 로더](/ko/guides/content-collections/#컬렉션-loader-정의)가 `.mdx` 파일의 콘텐츠를 로드하도록 구성되어 있는지 확인하세요: ```js title="src/content.config.ts" ins="mdx" -import { defineCollection, z } from 'astro:content'; +import { defineCollection } from 'astro:content'; import { glob } from 'astro/loaders'; +import { z } from 'astro/zod'; const blog = defineCollection({ loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/blog" }), diff --git a/src/content/docs/ko/guides/integrations-guide/react.mdx b/src/content/docs/ko/guides/integrations-guide/react.mdx index 5c71dd3f58316..f5eddbd251814 100644 --- a/src/content/docs/ko/guides/integrations-guide/react.mdx +++ b/src/content/docs/ko/guides/integrations-guide/react.mdx @@ -167,7 +167,7 @@ export function Like({ postId }: { postId: string }) { ```ts title="actions.ts" ins={3,11} import { defineAction, type SafeResult } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; import { getActionState } from '@astrojs/react/actions'; export const server = { diff --git a/src/content/docs/ko/guides/sessions.mdx b/src/content/docs/ko/guides/sessions.mdx index 0dfe37c3b4eda..3c84b2b22ddbe 100644 --- a/src/content/docs/ko/guides/sessions.mdx +++ b/src/content/docs/ko/guides/sessions.mdx @@ -89,7 +89,7 @@ export async function POST(context: APIContext) { ```ts title="src/actions/addToCart.ts" "context.session" import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { addToCart: defineAction({ diff --git a/src/content/docs/ko/recipes/build-forms-api.mdx b/src/content/docs/ko/recipes/build-forms-api.mdx index 7c22ead3d5acb..0d3ad52716216 100644 --- a/src/content/docs/ko/recipes/build-forms-api.mdx +++ b/src/content/docs/ko/recipes/build-forms-api.mdx @@ -429,29 +429,3 @@ HTML 양식을 사용하면 브라우저가 페이지를 새로 고치거나 새 - -{/* ## Extension: Use Zod to validate your form - -[Zod form data](https://www.npmjs.com/package/zod-form-data) builds on top of [Zod](https://github.com/colinhacks/zod) to validate your form using a schema. This simplifies your code, as it allows you to declare the fields and their requirements, and let Zod handle the validation. - -1. Install `zod` and `zod-form-data`. - - - - ```shell - npm i zod zod-form-data - ``` - - - ```shell - pnpm i zod zod-form-data - ``` - - - ```shell - yarn add zod zod-form-data - ``` - - - -2. In your API Route file, declare your schema using `zfd.formData` and export it. */} diff --git a/src/content/docs/ko/recipes/i18n.mdx b/src/content/docs/ko/recipes/i18n.mdx index 9adf5b51aaa91..54833e7a62f00 100644 --- a/src/content/docs/ko/recipes/i18n.mdx +++ b/src/content/docs/ko/recipes/i18n.mdx @@ -88,7 +88,8 @@ v4.0에서 Astro는 기본 및 지원되는 언어를 구성할 수 있게 해 ```ts //src/content.config.ts - import { defineCollection, z } from 'astro:content'; + import { defineCollection } from 'astro:content'; + import { z } from 'astro/zod'; const blogCollection = defineCollection({ schema: z.object({ diff --git a/src/content/docs/ko/reference/content-loader-reference.mdx b/src/content/docs/ko/reference/content-loader-reference.mdx index 94b87b237ec0c..ced0671c44792 100644 --- a/src/content/docs/ko/reference/content-loader-reference.mdx +++ b/src/content/docs/ko/reference/content-loader-reference.mdx @@ -181,7 +181,7 @@ const countries = defineCollection({ ```ts title=loader.ts import type { Loader, LoaderContext } from 'astro/loaders'; -import { z } from 'astro:content'; +import { z } from 'astro/zod'; import { loadFeedData } from "./feed.js"; // 로더에 필요한 모든 옵션을 정의 @@ -205,11 +205,12 @@ export function myLoader(options: { url: string, apiKey: string }): Loader { } ``` -이러한 구성 옵션은 컬렉션을 정의할 때 설정할 수 있습니다: +이러한 구성 옵션은 컬렉션을 정의할 때 설정할 수 있습니다. -```ts title="src/content.config.ts" {2,5-8} -import { defineCollection, z } from 'astro:content'; -import myLoader from '../../loader.ts'; +```ts title="src/content.config.ts" {3,6-9} +import { defineCollection } from 'astro:content'; +import { z } from 'astro/zod'; +import myLoader from '../../loader.ts'; const blog = defineCollection({ loader: myLoader({ diff --git a/src/content/docs/ko/reference/experimental-flags/live-content-collections.mdx b/src/content/docs/ko/reference/experimental-flags/live-content-collections.mdx index 7d7eff38e50b0..02677283af30a 100644 --- a/src/content/docs/ko/reference/experimental-flags/live-content-collections.mdx +++ b/src/content/docs/ko/reference/experimental-flags/live-content-collections.mdx @@ -487,7 +487,8 @@ if (error) { 빌드 타임 컬렉션과 마찬가지로, 라이브 컬렉션에서도 [Zod 스키마](/ko/guides/content-collections/#컬렉션-스키마-정의)를 사용하여 런타임에 데이터를 검증하고 변환할 수 있습니다. 스키마를 정의하면, 컬렉션을 쿼리할 때 [로더의 타입](#타입-안전-데이터)보다 더 높은 우선순위를 가집니다. ```ts title="src/live.config.ts" -import { z, defineLiveCollection } from 'astro:content'; +import { defineLiveCollection } from 'astro:content'; +import { z } from 'astro/zod'; import { apiLoader } from './loaders/api-loader'; const products = defineLiveCollection({ diff --git a/src/content/docs/ko/reference/legacy-flags.mdx b/src/content/docs/ko/reference/legacy-flags.mdx index 3ba04e4329d8a..daa9d9defe55d 100644 --- a/src/content/docs/ko/reference/legacy-flags.mdx +++ b/src/content/docs/ko/reference/legacy-flags.mdx @@ -42,7 +42,7 @@ export default defineConfig({ ```js // src/content/config.ts -import { defineCollection, z } from 'astro:content'; +import { defineCollection } from 'astro:content'; const blog = defineCollection({ }) diff --git a/src/content/docs/ko/reference/modules/astro-actions.mdx b/src/content/docs/ko/reference/modules/astro-actions.mdx index 75de06364fed2..d5fd0cd78d56e 100644 --- a/src/content/docs/ko/reference/modules/astro-actions.mdx +++ b/src/content/docs/ko/reference/modules/astro-actions.mdx @@ -42,7 +42,7 @@ import { ```ts title="src/actions/index.ts" import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; +import { z } from 'astro/zod'; export const server = { getGreeting: defineAction({ @@ -76,7 +76,7 @@ export const server = { **타입:** `ZodType | undefined`

-런타임에 핸들러 입력의 유효성을 검사하기 위해 Zod 유효성 검사기 (예: Zod 객체, Zod 구별된 유니온)를 허용하는 선택적 속성입니다. 액션이 유효성 검사에 실패하면 [`BAD_REQUEST` 오류](#actionerror)가 반환되고 `handler`가 호출되지 않습니다. +런타임에 핸들러 입력의 유효성을 검사하기 위해 [Zod 유효성 검사기](/ko/reference/modules/astro-zod/#일반적인-데이터-타입-유효성-검사기) (예: Zod 객체, Zod 구별된 유니온)를 허용하는 선택적 속성입니다. 액션이 유효성 검사에 실패하면 [`BAD_REQUEST` 오류](#actionerror)가 반환되고 `handler`가 호출되지 않습니다. `input`을 생략하면 `handler`는 JSON 요청의 경우 `unknown` 타입의 입력을, 양식 요청의 경우 `FormData` 타입의 입력을 받습니다. diff --git a/src/content/docs/ko/reference/modules/astro-content.mdx b/src/content/docs/ko/reference/modules/astro-content.mdx index 07897ddc2b4c0..b1d62fea14a99 100644 --- a/src/content/docs/ko/reference/modules/astro-content.mdx +++ b/src/content/docs/ko/reference/modules/astro-content.mdx @@ -18,7 +18,6 @@ import ReadMore from '~/components/ReadMore.astro'; ```js import { - z, defineCollection, getCollection, getEntry, @@ -75,7 +74,7 @@ export const collections = { blog };

-`schema`는 컬렉션에 대한 문서 프런트매터의 타입과 모양을 구성하는 선택적 Zod 객체입니다. 각 값은 [Zod 유효성 검사기](https://github.com/colinhacks/zod)를 사용해야 합니다. +`schema`는 컬렉션에 대한 문서 프런트매터의 타입과 모양을 구성하는 선택적 Zod 객체입니다. 각 값은 [Zod 유효성 검사기](/ko/reference/modules/astro-zod/#일반적인-데이터-타입-유효성-검사기)를 사용해야 합니다. 사용 예시는 [`콘텐츠 컬렉션` 가이드를 참조하세요](/ko/guides/content-collections/#컬렉션-스키마-정의). diff --git a/src/content/docs/ko/reference/modules/astro-zod.mdx b/src/content/docs/ko/reference/modules/astro-zod.mdx new file mode 100644 index 0000000000000..53603715ea5db --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-zod.mdx @@ -0,0 +1,120 @@ +--- +title: Zod API 참조 +sidebar: + label: 'astro/zod' +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import ReadMore from '~/components/ReadMore.astro'; + +[Zod](https://github.com/colinhacks/zod)는 TypeScript 기반의 스키마 선언 및 유효성 검사 라이브러리입니다. 이를 통해 간단한 타입(예: `string`, `number`)부터 복잡한 데이터 구조(예: 중첩 객체)에 이르기까지 데이터를 검증하고 변환하는 데 사용할 수 있는 스키마를 정의할 수 있습니다. + +`astro/zod` 모듈은 Zod v3의 모든 기능에 접근할 수 있도록 Zod를 다시 내보냅니다. 이 모듈을 사용하면 Zod를 직접 설치할 필요가 없습니다. 또한 [콘텐츠 컬렉션](/ko/guides/content-collections/) 또는 [액션](/ko/guides/actions/)과 같은 기능을 사용할 때 프로젝트가 Astro와 동일한 API 버전을 사용하도록 보장합니다. + +Zod의 작동 방식과 사용 가능한 기능에 대한 전체 문서는 [Zod v3 웹사이트](https://v3.zod.dev/)를 참조하세요. + +## `astro/zod`에서 가져오기 + +```ts +import { z } from 'astro/zod'; +``` + +### `z` + +

+ +**타입:** `object` +

+ +`z` 유틸리티는 다양한 데이터 타입에 대한 유효성 검사기, 데이터 작업에 필요한 메서드 및 타입에 접근할 수 있게 해줍니다. + +`z` 유틸리티에 대한 자세한 내용은 [Zod 문서](https://v3.zod.dev/?id=basic-usage)에서 확인하세요. + +#### 일반적인 데이터 타입 유효성 검사기 + +Zod를 사용하면 [원시 타입](https://v3.zod.dev/?id=primitives), [객체](https://v3.zod.dev/?id=objects), [배열](https://v3.zod.dev/?id=arrays) 등 모든 종류의 데이터의 유효성을 검사할 수 있습니다. + +다음 예시는 `user` 스키마를 생성하기 위한 다양한 일반적인 Zod 데이터 타입의 치트시트를 보여줍니다. + +```ts +import { z } from 'astro/zod'; + +const user = z.object({ + username: z.string(), + name: z.string().min(2), + email: z.string().email(), + role: z.enum(["admin", "editor"]), + language: z.enum(["en", "fr", "es"]).default("en"), + hobbies: z.array(z.string()), + age: z.number(), + isEmailConfirmed: z.boolean(), + inscriptionDate: z.date(), + website: z.string().url().optional(), +}); +``` + +#### Typescript 타입을 추출하기 + +Zod를 사용하면 [Zod의 타입 추론](https://v3.zod.dev/?id=type-inference)을 통해 어떤 스키마에서도 TypeScript 타입을 생성할 수 있습니다. 이는 [컴포넌트 props 정의](/ko/guides/typescript/#컴포넌트-props) 시 예상되는 데이터 구조를 설명하는 데 유용할 수 있습니다. + +다음 예시는 이전 스키마를 기반으로 `User` 타입을 생성합니다. + +```ts +type User = z.infer; + +/* 생성되는 `User` 타입은 다음과 같습니다. + * type User = { + * username: string; + * name: string; + * email: string; + * role: "admin" | "editor"; + * language: "en" | "fr" | "es"; + * hobbies: string[]; + * age: number; + * isEmailConfirmed: boolean; + * inscriptionDate: Date; + * website?: string | undefined; + * } + */ +``` + +#### Zod 메서드 사용하기 + +Zod는 오류 메시지를 사용자 정의하거나, 데이터를 변환하거나, 사용자 정의 유효성 검사 로직을 생성하는 등 다양한 [스키마 메서드](https://v3.zod.dev/?id=schema-methods)를 제공합니다. + +```ts +// 오류 메시지 사용자 정의 +const nonEmptyStrings = z.string().array().nonempty({ + message: "Can't be empty!", +}); + +// 스키마에서 데이터 유효성 검사 +nonEmptyStrings.parse([]); // 사용자 정의 오류가 발생합니다. + +// 장식용 이미지의 URL에서 객체 생성 +const decorativeImg = z.string().transform((value) => { + return { src: value, alt: "" }; +}); + +// 문자열에 대한 사용자 정의 유효성 검사기와 오류 메시지 생성 +const constrainedString = z + .string() + .refine((val) => val.length > 0 && val.length <= 255, { + message: "Must be between 1 and 255 characters.", + }); +``` + +### 직접 가져오기 + +대신, 모듈에서 [`z` 유틸리티](#z)에 있는 모든 Zod 유효성 검사기, 메서드 및 타입을 직접 가져올 수 있습니다. + +다음 예시는 날짜 문자열로부터 `Date` 객체를 생성하기 위해 `coerce`를 가져옵니다. + +```ts +import { coerce } from 'astro/zod'; + +const publishedOn = coerce.date(); +const publicationDate = publishedOn.parse("2025-12-03"); +``` diff --git a/src/content/docs/ko/tutorial/6-islands/4.mdx b/src/content/docs/ko/tutorial/6-islands/4.mdx index ac08119fbc381..402bf1f60f70c 100644 --- a/src/content/docs/ko/tutorial/6-islands/4.mdx +++ b/src/content/docs/ko/tutorial/6-islands/4.mdx @@ -120,7 +120,9 @@ import { Steps } from '@astrojs/starlight/components'; // glob 로더 가져오기 import { glob } from "astro/loaders"; // `astro:content`에서 유틸리티 가져오기 - import { z, defineCollection } from "astro:content"; + import { defineCollection } from "astro:content"; + // Zod 가져오기 + import { z } from "astro/zod"; // 각 컬렉션에 대한 `loader` 및 `schema` 정의 const blog = defineCollection({ loader: glob({ pattern: '**/[^_]*.md', base: "./src/blog" }),