AI 던전 게임
모듈 1: 모노레포 설정
먼저 새로운 모노레포를 생성합니다. 원하는 디렉토리 내에서 다음 명령어를 실행하세요:
npx create-nx-workspace@~20.6.3 dungeon-adventure --pm=pnpm --preset=ts --ci=skip --formatter=prettier
npx create-nx-workspace@~20.6.3 dungeon-adventure --pm=yarn --preset=ts --ci=skip --formatter=prettier
npx create-nx-workspace@~20.6.3 dungeon-adventure --pm=npm --preset=ts --ci=skip --formatter=prettier
npx create-nx-workspace@~20.6.3 dungeon-adventure --pm=bun --preset=ts --ci=skip --formatter=prettier
이 명령어는 dungeon-adventure
디렉토리 내에 NX 모노레포를 설정하며, 이후 vscode에서 열 수 있습니다. 파일 구조는 다음과 같아야 합니다:
디렉터리.nx/
- …
디렉터리.vscode/
- …
디렉터리node_modules/
- …
디렉터리packages/ 하위 프로젝트가 위치할 디렉토리
- …
- .gitignore
- .npmrc
- .prettierignore
- .prettierrc
- nx.json Nx CLI 및 모노레포 기본값 구성
- package.json 모든 node 종속성 정의
- pnpm-lock.yaml 또는 bun.lock, yarn.lock, package-lock.json (패키지 매니저에 따라 다름)
- pnpm-workspace.yaml (pnpm 사용 시)
- README.md
- tsconfig.base.json 모든 node 기반 하위 프로젝트가 상속할 기본 설정
- tsconfig.json
@aws/nx-plugin
의 컴포넌트를 모노레포에 추가하려면, dungeon-adventure
모노레포 루트에서 다음 명령어로 개발 의존성으로 설치해야 합니다:
pnpm add -Dw @aws/nx-plugin
yarn add -D @aws/nx-plugin
npm install --legacy-peer-deps -D @aws/nx-plugin
bun install -D @aws/nx-plugin
이제 @aws/nx-plugin
을 사용하여 다양한 하위 프로젝트를 생성할 준비가 되었습니다.
게임 API
먼저 Game API를 생성합니다. 다음 단계에 따라 GameApi
라는 tRPC API를 생성하세요:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#trpc-api
- 필수 매개변수 입력
- apiName: GameApi
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive
yarn nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive
npx nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive
bunx nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#trpc-api --apiName=GameApi --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성된 것을 확인할 수 있습니다.
ts#trpc-api로 업데이트된 파일
다음은 ts#trpc-api
제너레이터가 생성한 모든 파일 목록입니다. 파일 트리에서 강조 표시된 주요 파일을 살펴보겠습니다:
디렉터리packages/
디렉터리common/
디렉터리constructs/
디렉터리src/
디렉터리app/ 애플리케이션 특화 CDK 구성 요소
디렉터리http-apis/
- game-api.ts tRPC API 생성용 CDK 구성 요소
- index.ts
- …
- index.ts
디렉터리core/ 일반 CDK 구성 요소
- http-api.ts HTTP 기반 API 기본 CDK 구성 요소
- index.ts
- runtime-config.ts
- index.ts
- project.json
- …
디렉터리types/ 공유 타입
디렉터리src/
- index.ts
- runtime-config.ts CDK와 웹사이트 모두에서 사용되는 인터페이스 정의
- project.json
- …
디렉터리game-api/
디렉터리backend/ tRPC 구현 코드
디렉터리src/
디렉터리client/ TS 머신 간 호출에 사용되는 기본 클라이언트
- index.ts
- sigv4.ts
디렉터리middleware/ powertools 계측
- error.ts
- index.ts
- logger.ts
- metrics.ts
- tracer.ts
디렉터리procedures/ API 프로시저/경로 구현
- echo.ts
- index.ts
- init.ts 컨텍스트 및 미들웨어 설정
- local-server.ts 로컬 tRPC 서버 실행용
- router.ts 모든 프로시저를 정의하는 람다 핸들러 진입점
- project.json
- …
디렉터리schema/
디렉터리src/
디렉터리procedures/
- echo.ts
- index.ts
- project.json
- …
- eslint.config.mjs
- vitest.workspace.ts
주요 파일 몇 가지를 살펴보겠습니다:
import { awsLambdaRequestHandler, CreateAWSLambdaContextOptions,} from '@trpc/server/adapters/aws-lambda';import { echo } from './procedures/echo.js';import { t } from './init.js';import { APIGatewayProxyEventV2WithIAMAuthorizer } from 'aws-lambda';
export const router = t.router;
export const appRouter = router({ echo,});
export const handler = awsLambdaRequestHandler({ router: appRouter, createContext: ( ctx: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2WithIAMAuthorizer>, ) => ctx,});
export type AppRouter = typeof appRouter;
라우터는 tRPC API의 진입점이며 모든 API 메서드를 선언하는 곳입니다. 위에서 볼 수 있듯이 echo
메서드가 있으며 구현은 ./procedures/echo.ts
파일에 있습니다.
import { publicProcedure } from '../init.js';import { EchoInputSchema, EchoOutputSchema,} from ':dungeon-adventure/game-api-schema';
export const echo = publicProcedure .input(EchoInputSchema) .output(EchoOutputSchema) .query((opts) => ({ result: opts.input.message }));
이 파일은 echo
메서드의 구현이며, 입력 및 출력 데이터 구조를 강력하게 타입화합니다. 이러한 정의는 별칭으로 지정된 스키마 프로젝트 :dungeon-adventure/game-api-schema
에서 가져옵니다.
import { z } from 'zod';
export const EchoInputSchema = z.object({ message: z.string(),});
export type IEchoInput = z.TypeOf<typeof EchoInputSchema>;
export const EchoOutputSchema = z.object({ result: z.string(),});
export type IEchoOutput = z.TypeOf<typeof EchoOutputSchema>;
모든 tRPC 스키마 정의는 Zod를 사용하여 정의되며, z.TypeOf
구문을 통해 타입스크립트 타입으로 내보내집니다.
import { Construct } from 'constructs';import * as url from 'url';import { HttpApi } from '../../core/http-api.js';import { HttpIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';import { Runtime } from 'aws-cdk-lib/aws-lambda';
export class GameApi extends HttpApi { constructor(scope: Construct, id: string) { super(scope, id, { defaultAuthorizer: new HttpIamAuthorizer(), apiName: 'GameApi', runtime: Runtime.NODEJS_LATEST, handler: 'index.handler', handlerFilePath: url.fileURLToPath( new URL( '../../../../../../dist/packages/game-api/backend/bundle', import.meta.url, ), ), }); }}
이 CDK 구성 요소는 GameApi를 정의합니다. 보다시피 핸들러 파일 경로가 tRPC 백엔드 구현의 번들로 이미 구성되어 있어, cdk synth
시 NodeJsFunction을 사용하는 것과 달리 번들링이 발생하지 않습니다.
스토리 API
이제 Story API를 생성합니다. 다음 단계에 따라 StoryApi
라는 Fast API를 생성하세요:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - py#fast-api
- 필수 매개변수 입력
- name: StoryApi
- 클릭
Generate
pnpm nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive
yarn nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive
npx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive
bunx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive --dry-run
yarn nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive --dry-run
npx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive --dry-run
bunx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성된 것을 확인할 수 있습니다.
py#fast-api로 업데이트된 파일
다음은 py#fast-api
제너레이터가 생성/수정한 파일 목록입니다. 주요 파일을 살펴보겠습니다:
디렉터리.venv/ 모노레포용 단일 가상 환경
- …
디렉터리packages/
디렉터리common/
디렉터리constructs/
디렉터리src/
디렉터리app/ 애플리케이션 특화 CDK 구성 요소
디렉터리http-apis/
- story-api.ts Fast API 생성용 CDK 구성 요소
- index.ts 새 story-api 내보내기로 업데이트
- project.json story_api 빌드 종속성 추가로 업데이트
디렉터리types/ 공유 타입
디렉터리src/
- runtime-config.ts StoryApi 추가로 업데이트
디렉터리story_api/
디렉터리story_api/ 파이썬 모듈
- init.py powertools, FastAPI 및 미들웨어 설정
- main.py 모든 경로를 포함한 람다 진입점
디렉터리tests/
- …
- .python-version
- project.json
- pyproject.toml
- project.json
- .python-version 고정된 uv 파이썬 버전
- pyproject.toml
- uv.lock
import { Construct } from 'constructs';import * as url from 'url';import { HttpApi } from '../../core/http-api.js';import { HttpIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';import { Runtime } from 'aws-cdk-lib/aws-lambda';
export class StoryApi extends HttpApi { constructor(scope: Construct, id: string) { super(scope, id, { defaultAuthorizer: new HttpIamAuthorizer(), apiName: 'StoryApi', runtime: Runtime.PYTHON_3_12, handler: 'story_api.main.handler', handlerFilePath: url.fileURLToPath( new URL( '../../../../../../dist/packages/story_api/bundle', import.meta.url, ), ), }); }}
이 CDK 구성 요소는 StoryApi를 정의합니다. 핸들러 파일 경로가 Fast API 백엔드 구현의 번들로 구성되어 있어, cdk synth
시 PythonFunction 사용 시와 달리 번들링이 발생하지 않습니다.
export type ApiUrl = string;// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-empty-interfaceexport interface IRuntimeConfig { httpApis: { GameApi: ApiUrl; StoryApi: ApiUrl; };}
제너레이터가 AST 변환을 수행하여 기존 코드를 유지하고 업데이트하는 예시입니다. StoryApi
가 IRuntimeConfig
정의에 추가되어 프론트엔드에서 소비될 때 타입 안전성이 강제됩니다!
from .init import app, lambda_handler, tracer
handler = lambda_handler
@app.get("/")@tracer.capture_methoddef read_root(): return {"Hello": "World"}
모든 API 메서드가 정의될 곳입니다. 여기서는 GET /
경로에 매핑된 read_root
메서드가 있습니다. Pydantic을 사용하여 메서드 입력 및 출력을 선언하여 타입 안전성을 보장할 수 있습니다.
게임 UI: 웹사이트
이제 게임과 상호작용할 수 있는 UI를 생성합니다. 다음 단계에 따라 GameUI
라는 웹사이트를 생성하세요:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#cloudscape-website
- 필수 매개변수 입력
- name: GameUI
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive
yarn nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive
npx nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive
bunx nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#cloudscape-website --name=GameUI --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성된 것을 확인할 수 있습니다.
ts#cloudscape-website로 업데이트된 파일
다음은 ts#cloudscape-website
제너레이터가 생성한 주요 파일 목록입니다:
디렉터리packages/
디렉터리common/
디렉터리constructs/
디렉터리src/
디렉터리app/ 애플리케이션 특화 CDK 구성 요소
디렉터리static-websites/
- game-ui.ts Game UI 생성용 CDK 구성 요소
디렉터리core/
- static-website.ts 일반 정적 웹사이트 구성 요소
디렉터리game-ui/
디렉터리public/
- …
디렉터리src/
디렉터리components/
디렉터리AppLayout/
- index.ts 전체 페이지 레이아웃: 헤더, 푸터, 사이드바 등
- navitems.ts 사이드바 네비게이션 항목
디렉터리hooks/
- useAppLayout.tsx 알림, 페이지 스타일 등을 동적으로 설정
디렉터리routes/ @tanstack/react-router 파일 기반 경로
- index.tsx 루트 ’/’ 페이지가 ‘/welcome’으로 리디렉션
- __root.tsx 모든 페이지의 기본 컴포넌트
디렉터리welcome/
- index.tsx
- config.ts
- main.tsx React 진입점
- routeTree.gen.ts @tanstack/react-router에 의해 자동 업데이트
- styles.css
- index.html
- project.json
- vite.config.ts
- …
import * as url from 'url';import { Construct } from 'constructs';import { StaticWebsite } from '../../core/index.js';
export class GameUI extends StaticWebsite { constructor(scope: Construct, id: string) { super(scope, id, { websiteFilePath: url.fileURLToPath( new URL( '../../../../../../dist/packages/game-ui/bundle', import.meta.url, ), ), }); }}
이 CDK 구성 요소는 GameUI를 정의합니다. Vite 기반 UI의 번들 경로가 구성되어 있어 빌드 시 번들링이 game-ui 프로젝트의 빌드 대상 내에서 수행됩니다.
import React from 'react';import { createRoot } from 'react-dom/client';import { I18nProvider } from '@cloudscape-design/components/i18n';import messages from '@cloudscape-design/components/i18n/messages/all.en';import { RouterProvider, createRouter } from '@tanstack/react-router';import { routeTree } from './routeTree.gen';
import '@cloudscape-design/global-styles/index.css';
const router = createRouter({ routeTree });
// 타입 안전성을 위해 라우터 인스턴스 등록declare module '@tanstack/react-router' { interface Register { router: typeof router; }}
const root = document.getElementById('root');root && createRoot(root).render( <React.StrictMode> <I18nProvider locale="en" messages={[messages]}> <RouterProvider router={router} /> </I18nProvider> </React.StrictMode>, );
React가 마운트되는 진입점입니다. 개발 서버가 실행 중인 동안 routes
폴더에 파일을 생성하기만 하면 @tanstack/react-router
가 보일러플레이트 파일 설정을 자동으로 생성하고 routeTree.gen.ts
파일을 업데이트합니다. 이 파일은 모든 경로를 타입 안전하게 유지하므로 <Link>
사용 시 to
옵션에 유효한 경로만 표시됩니다. 자세한 내용은 @tanstack/react-router
문서를 참조하세요.
import { ContentLayout, Header, SpaceBetween, Container,} from '@cloudscape-design/components';import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/welcome/')({ component: RouteComponent,});
function RouteComponent() { return ( <ContentLayout header={<Header>Welcome</Header>}> <SpaceBetween size="l"> <Container>Welcome to your new Cloudscape website!</Container> </SpaceBetween> </ContentLayout> );}
/welcome
경로로 이동할 때 렌더링될 컴포넌트입니다. 개발 서버가 실행 중인 동안 파일 생성/이동 시 @tanstack/react-router
가 Route
를 관리합니다.
게임 UI: 인증
이제 Amazon Cognito를 통해 인증된 액세스가 필요한 Game UI를 구성합니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#cloudscape-website#auth
- 필수 매개변수 입력
- cognitoDomain: game-ui
- project: @dungeon-adventure/game-ui
- allowSignup: true
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
yarn nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
npx nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
bunx nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#cloudscape-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성/변경된 것을 확인할 수 있습니다.
ts#cloudscape-website#auth로 업데이트된 파일
다음은 ts#cloudscape-website#auth
제너레이터가 생성/수정한 파일 목록입니다:
디렉터리packages/
디렉터리common/
디렉터리constructs/
디렉터리src/
디렉터리core/
- user-identity.ts 사용자/ID 풀 생성용 CDK 구성 요소
디렉터리types/
디렉터리src/
- runtime-config.ts cognitoProps 추가로 업데이트
디렉터리game-ui/
디렉터리src/
디렉터리components/
디렉터리AppLayout/
- index.tsx 헤더에 로그인 사용자/로그아웃 추가
디렉터리CognitoAuth/
- index.ts Cognito 로그인 관리
디렉터리RuntimeConfig/
- index.tsx
runtime-config.json
가져와 컨텍스트로 제공
- index.tsx
디렉터리hooks/
- useRuntimeConfig.tsx
- main.tsx Cognito 추가로 업데이트
import CognitoAuth from './components/CognitoAuth';import RuntimeConfigProvider from './components/RuntimeConfig';import React from 'react';import { createRoot } from 'react-dom/client';import { I18nProvider } from '@cloudscape-design/components/i18n';import messages from '@cloudscape-design/components/i18n/messages/all.en';import { RouterProvider, createRouter } from '@tanstack/react-router';import { routeTree } from './routeTree.gen';import '@cloudscape-design/global-styles/index.css';const router = createRouter({ routeTree });// 라우터 인스턴스 타입 안전성 등록declare module '@tanstack/react-router' { interface Register { router: typeof router; }}const root = document.getElementById('root');root && createRoot(root).render( <React.StrictMode> <I18nProvider locale="en" messages={[messages]}> <RuntimeConfigProvider> <CognitoAuth> <RouterProvider router={router} /> </CognitoAuth> </RuntimeConfigProvider> </I18nProvider> </React.StrictMode>, );
RuntimeConfigProvider
와 CognitoAuth
컴포넌트가 AST 변환을 통해 main.tsx
파일에 추가되었습니다. 이를 통해 CognitoAuth
컴포넌트가 runtime-config.json
을 가져와 필요한 Cognito 연결 구성을 사용하여 백엔드 호출을 올바른 대상으로 수행할 수 있습니다.
게임 UI: Story API 연결
이전에 생성한 Story API에 Game UI를 연결합니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - api-connection
- 필수 매개변수 입력
- sourceProject: @dungeon-adventure/game-ui
- targetProject: dungeon_adventure.story_api
- 클릭
Generate
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive --dry-run
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive --dry-run
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive --dry-run
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=dungeon_adventure.story_api --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성/변경된 것을 확인할 수 있습니다.
UI -> FastAPI api-connection 업데이트된 파일
다음은 api-connection
제너레이터가 생성/수정한 파일 목록입니다:
디렉터리packages/
디렉터리game-ui/
디렉터리src/
디렉터리hooks/
- useSigV4.tsx StoryApi 요청 서명용
- useStoryApiClient.tsx StoryApi 클라이언트 생성 훅
- useStoryApi.tsx TanStack Query 사용 StoryApi 상호작용 훅
디렉터리components/
- QueryClientProvider.tsx TanStack Query 클라이언트 제공자
- StoryApiProvider.tsx StoryApi TanStack Query 훅 제공자
- main.tsx QueryClientProvider 및 StoryApiProvider 계측
- .gitignore 생성된 클라이언트 파일 무시
- project.json openapi 훅 생성 대상 추가로 업데이트
- …
디렉터리story_api/
디렉터리scripts/
- generate_open_api.py
- project.json openapi.json 파일 생성으로 업데이트
import { StoryApi } from '../generated/story-api/client.gen';import { useSigV4 } from './useSigV4';import { useRuntimeConfig } from './useRuntimeConfig';import { useMemo } from 'react';
export const useStoryApi = (): StoryApi => { const runtimeConfig = useRuntimeConfig(); const apiUrl = runtimeConfig.httpApis.StoryApi; const sigv4Client = useSigV4(); return useMemo( () => new StoryApi({ url: apiUrl, fetch: sigv4Client, }), [apiUrl, sigv4Client], );};
이 훅은 StoryApi
에 인증된 API 요청을 수행하는 데 사용됩니다. 구현에서 볼 수 있듯이 빌드 시 생성되는 StoryApi
를 사용하므로 코드를 빌드하기 전까지 IDE에서 오류가 표시됩니다. 자세한 내용은 React to FastAPI 가이드를 참조하세요.
import { createContext, FC, PropsWithChildren, useMemo } from 'react';import { useStoryApiClient } from '../hooks/useStoryApiClient';import { StoryApiOptionsProxy } from '../generated/story-api/options-proxy.gen';
export const StoryApiContext = createContext<StoryApiOptionsProxy | undefined>( undefined,);
export const StoryApiProvider: FC<PropsWithChildren> = ({ children }) => { const client = useStoryApiClient(); const optionsProxy = useMemo( () => new StoryApiOptionsProxy({ client }), [client], );
return ( <StoryApiContext.Provider value={optionsProxy}> {children} </StoryApiContext.Provider> );};
export default StoryApiProvider;
이 제공자 컴포넌트는 useStoryApiClient
훅을 사용하여 StoryApiOptionsProxy
를 인스턴스화합니다. 이는 TanStack Query 훅에 대한 옵션을 구성하는 데 사용됩니다. useStoryApi
훅을 사용하여 이 옵션 프록시에 접근할 수 있으며, tRPC API와 일관된 방식으로 FastAPI와 상호작용할 수 있습니다.
useStoryApiClient
가 스트리밍 API에 대한 비동기 반복자를 제공하므로, 이 튜토리얼에서는 기본 클라이언트를 직접 사용할 것입니다.
게임 UI: Game API 연결
이전에 생성한 Game API에 Game UI를 연결합니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - api-connection
- 필수 매개변수 입력
- sourceProject: @dungeon-adventure/game-ui
- targetProject: @dungeon-adventure/game-api-backend
- 클릭
Generate
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive --dry-run
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive --dry-run
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive --dry-run
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api-backend --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성/변경된 것을 확인할 수 있습니다.
UI -> tRPC api-connection 업데이트된 파일
다음은 api-connection
제너레이터가 생성/수정한 파일 목록입니다:
디렉터리packages/
디렉터리game-ui/
디렉터리src/
디렉터리components/
디렉터리TrpcClients/
- index.tsx
- TrpcApis.tsx 구성된 모든 tRPC API
- TrpcClientProviders.tsx tRPC API별 클라이언트 제공자 생성
- TrpcProvider.tsx
디렉터리hooks/
- useGameApi.tsx GameApi 호출 훅
- main.tsx trpc 클라이언트 제공자 주입
- package.json
import { TrpcApis } from '../components/TrpcClients';
export const useGameApi = () => TrpcApis.GameApi.useTRPC();
이 훅은 tRPC의 최신 React Query 통합을 사용하여 추가 추상화 계층 없이 @tanstack/react-query
와 직접 상호작용할 수 있게 합니다. 사용 예시는 tRPC 훅 사용 가이드를 참조하세요.
import TrpcClientProviders from './components/TrpcClients';import QueryClientProvider from './components/QueryClientProvider';import CognitoAuth from './components/CognitoAuth';import RuntimeConfigProvider from './components/RuntimeConfig';import React from 'react';import { createRoot } from 'react-dom/client';import { I18nProvider } from '@cloudscape-design/components/i18n';import messages from '@cloudscape-design/components/i18n/messages/all.en';import { RouterProvider, createRouter } from '@tanstack/react-router';import { routeTree } from './routeTree.gen';import '@cloudscape-design/global-styles/index.css';const router = createRouter({ routeTree });// 라우터 인스턴스 타입 안전성 등록declare module '@tanstack/react-router' { interface Register { router: typeof router; }}const root = document.getElementById('root');root && createRoot(root).render( <React.StrictMode> <I18nProvider locale="en" messages={[messages]}> <RuntimeConfigProvider> <CognitoAuth> <QueryClientProvider> <TrpcClientProviders> <RouterProvider router={router} /> </TrpcClientProviders> </QueryClientProvider> </CognitoAuth> </RuntimeConfigProvider> </I18nProvider> </React.StrictMode>, );
main.tsx
파일이 AST 변환을 통해 tRPC 제공자를 주입하도록 업데이트되었습니다.
게임 UI: 인프라
마지막으로 생성할 하위 프로젝트는 CDK 인프라입니다. 다음 단계에 따라 생성하세요:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#infra
- 필수 매개변수 입력
- name: infra
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
yarn nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
npx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
bunx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive --dry-run
파일 트리에 몇 가지 새 파일이 생성/변경된 것을 확인할 수 있습니다.
ts#infra로 업데이트된 파일
다음은 ts#infra
제너레이터가 생성/수정한 파일 목록입니다:
디렉터리packages/
디렉터리common/
디렉터리constructs/
디렉터리src/
디렉터리core/
디렉터리cfn-guard-rules/
- *.guard
- cfn-guard.ts
- index.ts
디렉터리infra
디렉터리src/
디렉터리stacks/
- application-stack.ts CDK 리소스 정의
- index.ts
- main.ts 모든 스택 정의 진입점
- cdk.json
- project.json
- …
- package.json
- tsconfig.json 참조 추가
- tsconfig.base.json 별칭 추가
import { ApplicationStack } from './stacks/application-stack.js';import { App, CfnGuardValidator, RuleSet,} from ':dungeon-adventure/common-constructs';
const app = new App({ policyValidationBeta1: [new CfnGuardValidator(RuleSet.AWS_PROTOTYPING)],});
// CLI 자격 증명을 사용하여 자체 샌드박스 환경 배포new ApplicationStack(app, 'dungeon-adventure-infra-sandbox', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION, }, crossRegionReferences: true,});
app.synth();
CDK 애플리케이션의 진입점입니다.
cfn-guard
를 사용하여 구성된 규칙 세트 기반 인프라 유효성 검사를 수행하도록 구성되어 있습니다. 이는 합성 후 계측됩니다.
import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';
export class ApplicationStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 스택을 정의하는 코드 }}
던전 어드벤처 게임을 구축하기 위해 CDK 구성요소를 인스턴스화할 곳입니다.
인프라 업데이트
packages/infra/src/stacks/application-stack.ts
를 업데이트하여 이미 생성된 구성요소를 인스턴스화합니다:
import { GameApi, GameUI, StoryApi, UserIdentity,} from ':dungeon-adventure/common-constructs';import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';
export class ApplicationStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 스택을 정의하는 코드 const userIdentity = new UserIdentity(this, 'UserIdentity');
const gameApi = new GameApi(this, 'GameApi'); const storyApi = new StoryApi(this, 'StoryApi');
// 인증된 역할에 API 호출 권한 부여 [storyApi, gameApi].forEach((api) => api.grantInvokeAccess(userIdentity.identityPool.authenticatedRole), );
// runtime-config.json 자동 구성 위해 마지막에 인스턴스화 new GameUI(this, 'GameUI'); }}
코드 빌드
Nx 명령어
단일 vs 다중 대상
run-many
명령어는 여러 하위 프로젝트에서 대상(--all
사용 시 모두 대상)을 실행하며 종속성이 올바른 순서로 실행되도록 합니다.
단일 프로젝트 대상에 대해 빌드(또는 다른 작업)를 트리거하려면 해당 프로젝트에서 직접 대상을 실행할 수 있습니다. 예를 들어 @dungeon-adventure/infra
프로젝트를 빌드하려면 다음 명령어를 실행합니다:
pnpm nx run @dungeon-adventure/infra:build
yarn nx run @dungeon-adventure/infra:build
npx nx run @dungeon-adventure/infra:build
bunx nx run @dungeon-adventure/infra:build
종속성 시각화
다음 명령어로 종속성을 시각화할 수 있습니다:
pnpm nx graph
yarn nx graph
npx nx graph
bunx nx graph

캐싱
Nx는 개발 속도 향상을 위해 캐싱을 사용합니다. 캐시를 사용하지 않고 빌드하려면 --skip-nx-cache
인수를 추가하세요:
pnpm nx run @dungeon-adventure/infra:build --skip-nx-cache
yarn nx run @dungeon-adventure/infra:build --skip-nx-cache
npx nx run @dungeon-adventure/infra:build --skip-nx-cache
bunx nx run @dungeon-adventure/infra:build --skip-nx-cache
캐시를 지우려면 다음 명령어를 실행합니다:
pnpm nx reset
yarn nx reset
npx nx reset
bunx nx reset
pnpm nx run-many --target build --all
yarn nx run-many --target build --all
npx nx run-many --target build --all
bunx nx run-many --target build --all
다음과 같은 프롬프트가 표시됩니다:
NX The workspace is out of sync
[@nx/js:typescript-sync]: Some TypeScript configuration files are missing project references to the projects they depend on or contain outdated project references.
This will result in an error in CI.
? Would you like to sync the identified changes to get your workspace up to date? …Yes, sync the changes and run the tasksNo, run the tasks without syncing the changes
이 메시지는 NX가 자동으로 업데이트할 수 있는 파일을 감지했음을 나타냅니다. 이 경우 타입스크립트 참조가 설정되지 않은 tsconfig.json
파일을 가리킵니다. Yes, sync the changes and run the tasks 옵션을 선택하여 진행합니다. 동기화 제너레이터가 누락된 타입스크립트 참조를 자동으로 추가하므로 모든 IDE 가져오기 오류가 해결됩니다!
모든 빌드 아티팩트는 모노레포 루트의 dist/
폴더 내에서 사용 가능합니다. 생성된 파일을 정리하려면 dist/
폴더를 삭제하면 됩니다.
축하합니다! 던전 어드벤처 게임의 핵심을 구현하기 위한 모든 하위 프로젝트를 성공적으로 생성했습니다. 🎉🎉🎉