Jeu de Donjon IA
Module 1 : Configuration du monorepo
Section intitulée « Module 1 : Configuration du monorepo »Nous allons commencer par créer un nouveau monorepo. Depuis le répertoire de votre choix, exécutez la commande suivante :
npx create-nx-workspace@~21.0.3 dungeon-adventure --pm=pnpm --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 dungeon-adventure --pm=yarn --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 dungeon-adventure --pm=npm --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 dungeon-adventure --pm=bun --preset=@aws/nx-plugin --ci=skip
Cela configurera un monorepo NX dans le répertoire dungeon-adventure
que vous pourrez ensuite ouvrir dans vscode. Il devrait ressembler à ceci :
Répertoire.nx/
- …
Répertoire.vscode/
- …
Répertoirenode_modules/
- …
Répertoirepackages/ emplacement de vos sous-projets
- …
- .gitignore
- .npmrc
- .prettierignore
- .prettierrc
- nx.json configure les paramètres par défaut du CLI Nx et du monorepo
- package.json toutes les dépendances Node sont définies ici
- pnpm-lock.yaml ou bun.lock, yarn.lock, package-lock.json selon le gestionnaire de paquets
- pnpm-workspace.yaml si vous utilisez pnpm
- README.md
- tsconfig.base.json étendu par tous les sous-projets Node
- tsconfig.json
Nous sommes maintenant prêts à créer nos différents sous-projets en utilisant le @aws/nx-plugin
.
API de jeu
Section intitulée « API de jeu »Commençons par créer notre API de jeu. Pour cela, créons une API tRPC appelée GameApi
en suivant les étapes ci-dessous :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - ts#trpc-api
- Remplissez les paramètres requis
- name: GameApi
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive
yarn nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive
npx nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive
bunx nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#trpc-api --name=GameApi --no-interactive --dry-run
Vous devriez voir apparaître de nouveaux fichiers dans votre arborescence.
Fichiers modifiés par ts#trpc-api
Voici la liste des fichiers générés par le générateur ts#trpc-api
. Examinons les fichiers clés mis en évidence :
Répertoirepackages/
Répertoirecommon/
Répertoireconstructs/
Répertoiresrc/
Répertoireapp/ constructions CDK spécifiques à l’application
Répertoireapis/
- game-api.ts construction CDK pour l’API tRPC
- index.ts
- …
- index.ts
Répertoirecore/ constructions CDK génériques
Répertoireapi/
- rest-api.ts construction de base pour une API Gateway Rest
- trpc-utils.ts utilitaires pour les constructions CDK tRPC
- utils.ts utilitaires pour les constructions d’API
- index.ts
- runtime-config.ts
- index.ts
- project.json
- …
Répertoiretypes/ types partagés
Répertoiresrc/
- index.ts
- runtime-config.ts définition d’interface utilisée par CDK et le site web
- project.json
- …
Répertoiregame-api/ API tRPC
Répertoiresrc/
Répertoireclient/ client vanilla pour appels machine à machine
- index.ts
- sigv4.ts
Répertoiremiddleware/ instrumentation Powertools
- error.ts
- index.ts
- logger.ts
- metrics.ts
- tracer.ts
Répertoireschema/ définitions des entrées/sorties de l’API
- echo.ts
Répertoireprocedures/ implémentations des procédures/routes de l’API
- echo.ts
- index.ts
- init.ts configure le contexte et middleware
- local-server.ts pour exécuter le serveur tRPC localement
- router.ts point d’entrée du handler Lambda définissant toutes les procédures
- project.json
- …
- eslint.config.mjs
- vitest.workspace.ts
Examinons quelques fichiers clés :
import { awsLambdaRequestHandler, CreateAWSLambdaContextOptions,} from '@trpc/server/adapters/aws-lambda';import { echo } from './procedures/echo.js';import { t } from './init.js';import { APIGatewayProxyEvent } from 'aws-lambda';
export const router = t.router;
export const appRouter = router({ echo,});
export const handler = awsLambdaRequestHandler({ router: appRouter, createContext: ( ctx: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>, ) => ctx, responseMeta: () => ({ headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', }, }),});
export type AppRouter = typeof appRouter;
Le routeur définit le point d’entrée de votre API tRPC et déclare toutes les méthodes. Nous avons ici une méthode echo
dont l’implémentation se trouve dans ./procedures/echo.ts
.
import { publicProcedure } from '../init.js';import { EchoInputSchema, EchoOutputSchema,} from '../schema/echo.js';
export const echo = publicProcedure .input(EchoInputSchema) .output(EchoOutputSchema) .query((opts) => ({ result: opts.input.message }));
Ce fichier implémente la méthode echo
avec des types stricts pour les entrées et sorties.
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>;
Les schémas tRPC sont définis avec Zod et exportés comme types TypeScript via z.TypeOf
.
import { Construct } from 'constructs';import * as url from 'url';import { Code, Runtime, Function, FunctionProps, Tracing,} from 'aws-cdk-lib/aws-lambda';import { AuthorizationType, Cors, LambdaIntegration,} from 'aws-cdk-lib/aws-apigateway';import { Duration, Stack } from 'aws-cdk-lib';import { PolicyDocument, PolicyStatement, Effect, AccountPrincipal, AnyPrincipal,} from 'aws-cdk-lib/aws-iam';import { IntegrationBuilder, RestApiIntegration,} from '../../core/api/utils.js';import { RestApi } from '../../core/api/rest-api.js';import { Procedures, routerToOperations } from '../../core/api/trpc-utils.js';import { AppRouter, appRouter } from ':dungeon-adventure/game-api';
// Type union pour les noms d'opérations de l'APItype Operations = Procedures<AppRouter>;
/** * Propriétés pour la création d'une construction GameApi * * @template TIntegrations - Map des noms d'opérations vers leurs intégrations */export interface GameApiProps< TIntegrations extends Record<Operations, RestApiIntegration>,> { /** * Map des noms d'opérations vers leurs intégrations API Gateway */ integrations: TIntegrations;}
/** * Construction CDK pour configurer une API Gateway REST API pour GameApi * @template TIntegrations - Map des noms d'opérations vers leurs intégrations */export class GameApi< TIntegrations extends Record<Operations, RestApiIntegration>,> extends RestApi<Operations, TIntegrations> { /** * Crée des intégrations par défaut pour toutes les opérations, implémentant chaque opération * comme une fonction Lambda distincte. * * @param scope - Portée de la construction CDK * @returns Un IntegrationBuilder avec les intégrations Lambda par défaut */ public static defaultIntegrations = (scope: Construct) => { return IntegrationBuilder.rest({ operations: routerToOperations(appRouter), defaultIntegrationOptions: { runtime: Runtime.NODEJS_LATEST, handler: 'index.handler', code: Code.fromAsset( url.fileURLToPath( new URL( '../../../../../../dist/packages/game-api/bundle', import.meta.url, ), ), ), timeout: Duration.seconds(30), tracing: Tracing.ACTIVE, environment: { AWS_CONNECTION_REUSE_ENABLED: '1', }, } satisfies FunctionProps, buildDefaultIntegration: (op, props: FunctionProps) => { const handler = new Function(scope, `GameApi${op}Handler`, props); return { handler, integration: new LambdaIntegration(handler) }; }, }); };
constructor( scope: Construct, id: string, props: GameApiProps<TIntegrations>, ) { super(scope, id, { apiName: 'GameApi', defaultMethodOptions: { authorizationType: AuthorizationType.IAM, }, defaultCorsPreflightOptions: { allowOrigins: Cors.ALL_ORIGINS, allowMethods: Cors.ALL_METHODS, }, policy: new PolicyDocument({ statements: [ // Autorise les credentials AWS du compte de déploiement à appeler l'API new PolicyStatement({ effect: Effect.ALLOW, principals: [new AccountPrincipal(Stack.of(scope).account)], actions: ['execute-api:Invoke'], resources: ['execute-api:/*'], }), // Autorise les requêtes OPTIONS non authentifiées pour les prévols navigateurs new PolicyStatement({ effect: Effect.ALLOW, principals: [new AnyPrincipal()], actions: ['execute-api:Invoke'], resources: ['execute-api:/*/OPTIONS/*'], }), ], }), operations: routerToOperations(appRouter), ...props, }); }}
Cette construction CDK pour GameApi fournit une méthode defaultIntegrations
créant une fonction Lambda par procédure tRPC, pointant vers l’implémentation pré-bundle. Le bundling ne se fait pas au moment du cdk synth
car il est déjà effectué lors du build du projet.
API de scénario
Section intitulée « API de scénario »Créons maintenant notre API de scénario. Pour cela, créons une API FastAPI appelée StoryApi
:
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - py#fast-api
- Remplissez les paramètres requis
- name: StoryApi
- moduleName: story_api
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive
yarn nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive
npx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive
bunx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive --dry-run
yarn nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive --dry-run
npx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive --dry-run
bunx nx g @aws/nx-plugin:py#fast-api --name=StoryApi --moduleName=story_api --no-interactive --dry-run
De nouveaux fichiers devraient apparaître dans votre arborescence.
Fichiers modifiés par py#fast-api
Voici les fichiers clés générés par le générateur py#fast-api
:
Répertoire.venv/ environnement virtuel unique pour le monorepo
- …
Répertoirepackages/
Répertoirecommon/
Répertoireconstructs/
Répertoiresrc/
Répertoireapp/
Répertoireapis/
- story-api.ts construction CDK pour l’API FastAPI
- index.ts mis à jour pour exporter la nouvelle API
- project.json ajoute une dépendance de build sur story_api
Répertoiretypes/
Répertoiresrc/
- runtime-config.ts mis à jour avec StoryApi
Répertoirestory_api/
Répertoirestory_api/ module Python
- init.py configure Powertools, FastAPI et middleware
- main.py point d’entrée Lambda contenant toutes les routes
Répertoiretests/
- …
- .python-version
- project.json
- pyproject.toml
- .python-version version Python figée
- pyproject.toml
- uv.lock
import { Construct } from 'constructs';import * as url from 'url';import { Code, Runtime, Function, FunctionProps, Tracing,} from 'aws-cdk-lib/aws-lambda';import { AuthorizationType, Cors, LambdaIntegration,} from 'aws-cdk-lib/aws-apigateway';import { Duration, Stack } from 'aws-cdk-lib';import { PolicyDocument, PolicyStatement, Effect, AccountPrincipal, AnyPrincipal,} from 'aws-cdk-lib/aws-iam';import { IntegrationBuilder, RestApiIntegration,} from '../../core/api/utils.js';import { RestApi } from '../../core/api/rest-api.js';import { OPERATION_DETAILS, Operations,} from '../../generated/story-api/metadata.gen.js';
/** * Propriétés pour la création de StoryApi */export interface StoryApiProps< TIntegrations extends Record<Operations, RestApiIntegration>,> { integrations: TIntegrations;}
/** * Construction CDK pour l'API StoryApi */export class StoryApi< TIntegrations extends Record<Operations, RestApiIntegration>,> extends RestApi<Operations, TIntegrations> { public static defaultIntegrations = (scope: Construct) => { return IntegrationBuilder.rest({ operations: OPERATION_DETAILS, defaultIntegrationOptions: { runtime: Runtime.PYTHON_3_12, handler: 'story_api.main.handler', code: Code.fromAsset( url.fileURLToPath( new URL( '../../../../../../dist/packages/story_api/bundle', import.meta.url, ), ), ), timeout: Duration.seconds(30), tracing: Tracing.ACTIVE, environment: { AWS_CONNECTION_REUSE_ENABLED: '1', }, } satisfies FunctionProps, buildDefaultIntegration: (op, props: FunctionProps) => { const handler = new Function(scope, `StoryApi${op}Handler`, props); return { handler, integration: new LambdaIntegration(handler) }; }, }); };
constructor( scope: Construct, id: string, props: StoryApiProps<TIntegrations>, ) { super(scope, id, { apiName: 'StoryApi', defaultMethodOptions: { authorizationType: AuthorizationType.IAM, }, defaultCorsPreflightOptions: { allowOrigins: Cors.ALL_ORIGINS, allowMethods: Cors.ALL_METHODS, }, policy: new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, principals: [new AccountPrincipal(Stack.of(scope).account)], actions: ['execute-api:Invoke'], resources: ['execute-api:/*'], }), new PolicyStatement({ effect: Effect.ALLOW, principals: [new AnyPrincipal()], actions: ['execute-api:Invoke'], resources: ['execute-api:/*/OPTIONS/*'], }), ], }), operations: OPERATION_DETAILS, ...props, }); }}
Cette construction CDK pour StoryApi crée une fonction Lambda par opération FastAPI, utilisant le bundle pré-généré.
export type ApiUrl = string;export interface IRuntimeConfig { apis: { GameApi: ApiUrl; StoryApi: ApiUrl; };}
Le générateur a mis à jour IRuntimeConfig
via une transformation AST, ajoutant StoryApi
pour la sécurité des types frontend.
from .init import app, lambda_handler, tracer
handler = lambda_handler
@app.get("/")@tracer.capture_methoddef read_root(): return {"Hello": "World"}
Ce fichier définit les méthodes de l’API avec Pydantic pour la validation des types.
Interface utilisateur du jeu : Site web
Section intitulée « Interface utilisateur du jeu : Site web »Créons maintenant l’interface utilisateur. Utilisons le générateur pour un site React :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - ts#react-website
- Remplissez les paramètres requis
- name: GameUI
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive
yarn nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive
npx nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive
bunx nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#react-website --name=GameUI --no-interactive --dry-run
De nouveaux fichiers devraient apparaître.
Fichiers modifiés par ts#react-website
Fichiers clés générés par ts#react-website
:
Répertoirepackages/
Répertoirecommon/
Répertoireconstructs/
Répertoiresrc/
Répertoireapp/
Répertoirestatic-websites/
- game-ui.ts construction CDK pour l’UI
Répertoirecore/
- static-website.ts construction générique de site statique
Répertoiregame-ui/
Répertoirepublic/
- …
Répertoiresrc/
Répertoirecomponents/
RépertoireAppLayout/
- index.ts layout global
- navitems.ts éléments de navigation
Répertoirehooks/
- useAppLayout.tsx gestion dynamique du layout
Répertoireroutes/ routage basé fichiers avec @tanstack/react-router
- index.tsx redirection vers ‘/welcome’
- __root.tsx composant de base
Répertoirewelcome/
- index.tsx
- config.ts
- main.tsx point d’entrée React
- routeTree.gen.ts généré automatiquement
- 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, ), ), }); }}
Cette construction CDK pointe vers le bundle Vite généré.
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>, );
Point d’entrée React configurant le routage basé fichiers. Consultez la doc @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> );}
Composant pour la route /welcome
, géré automatiquement par le routeur.
Interface utilisateur du jeu : Authentification
Section intitulée « Interface utilisateur du jeu : Authentification »Configurons l’authentification via Amazon Cognito :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - ts#react-website#auth
- Remplissez les paramètres requis
- cognitoDomain: game-ui
- project: @dungeon-adventure/game-ui
- allowSignup: true
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
yarn nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
npx nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
bunx nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#react-website#auth --cognitoDomain=game-ui --project=@dungeon-adventure/game-ui --allowSignup=true --no-interactive --dry-run
Des fichiers ont été modifiés/ajoutés.
Fichiers modifiés par ts#react-website#auth
Fichiers clés :
Répertoirepackages/
Répertoirecommon/
Répertoireconstructs/
Répertoiresrc/
Répertoirecore/
- user-identity.ts construction CDK pour Cognito
Répertoiretypes/
Répertoiresrc/
- runtime-config.ts ajout de cognitoProps
Répertoiregame-ui/
Répertoiresrc/
Répertoirecomponents/
RépertoireAppLayout/
- index.tsx ajout utilisateur connecté/déconnexion
RépertoireCognitoAuth/
- index.ts gestion de l’authentification
RépertoireRuntimeConfig/
- index.tsx récupère runtime-config.json
Répertoirehooks/
- useRuntimeConfig.tsx
- main.tsx ajout de 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>, );
Les composants RuntimeConfigProvider
et CognitoAuth
ont été ajoutés pour l’authentification via runtime-config.json
.
Interface utilisateur du jeu : Connexion à Story API
Section intitulée « Interface utilisateur du jeu : Connexion à Story API »Connectons l’UI à Story API :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - api-connection
- Remplissez les paramètres requis
- sourceProject: @dungeon-adventure/game-ui
- targetProject: dungeon_adventure.story_api
- Cliquez sur
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
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
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
Des fichiers ont été modifiés.
Fichiers modifiés par la connexion UI -> FastAPI
Fichiers clés :
Répertoirepackages/
Répertoiregame-ui/
Répertoiresrc/
Répertoirehooks/
- useSigV4.tsx signature des requêtes
- useStoryApiClient.tsx client StoryApi
- useStoryApi.tsx hook avec TanStack Query
Répertoirecomponents/
- QueryClientProvider.tsx fournisseur TanStack Query
- StoryApiProvider.tsx fournisseur du hook
- main.tsx injection des fournisseurs
Répertoirestory_api/
Répertoirescripts/
- generate_open_api.py
- project.json génération 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.apis.StoryApi; const sigv4Client = useSigV4(); return useMemo( () => new StoryApi({ url: apiUrl, fetch: sigv4Client, }), [apiUrl, sigv4Client], );};
Hook pour appels authentifiés à StoryApi. Le client est généré au build.
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;
Fournisseur utilisant StoryApiOptionsProxy
pour les options TanStack Query.
Interface utilisateur du jeu : Connexion à Game API
Section intitulée « Interface utilisateur du jeu : Connexion à Game API »Connectons l’UI à Game API :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - api-connection
- Remplissez les paramètres requis
- sourceProject: @dungeon-adventure/game-ui
- targetProject: @dungeon-adventure/game-api
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive --dry-run
yarn nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive --dry-run
npx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive --dry-run
bunx nx g @aws/nx-plugin:api-connection --sourceProject=@dungeon-adventure/game-ui --targetProject=@dungeon-adventure/game-api --no-interactive --dry-run
Des fichiers ont été modifiés.
Fichiers modifiés par la connexion UI -> tRPC
Fichiers clés :
Répertoirepackages/
Répertoiregame-ui/
Répertoiresrc/
Répertoirecomponents/
- GameApiClientProvider.tsx client tRPC
Répertoirehooks/
- useGameApi.tsx hook tRPC
- main.tsx injection des fournisseurs tRPC
import { GameApiTRCPContext } from '../components/GameApiClientProvider';
export const useGameApi = GameApiTRCPContext.useTRPC;
Hook utilisant l’intégration React Query de tRPC.
import GameApiClientProvider from './components/GameApiClientProvider';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> <GameApiClientProvider> <RouterProvider router={router} /> </GameApiClientProvider> </QueryClientProvider> </CognitoAuth> </RuntimeConfigProvider> </I18nProvider> </React.StrictMode>, );
Injection des fournisseurs tRPC via transformation AST.
Infrastructure de l’interface utilisateur
Section intitulée « Infrastructure de l’interface utilisateur »Créons le projet d’infrastructure CDK :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - ts#infra
- Remplissez les paramètres requis
- name: infra
- Cliquez sur
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
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
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
Des fichiers ont été modifiés.
Fichiers modifiés par ts#infra
Fichiers clés :
Répertoirepackages/
Répertoirecommon/
Répertoireconstructs/
Répertoiresrc/
Répertoirecore/
Répertoirecfn-guard-rules/
- *.guard
- cfn-guard.ts
- index.ts
Répertoireinfra
Répertoiresrc/
Répertoirestacks/
- application-stack.ts ressources CDK
- index.ts
- main.ts point d’entrée CDK
- cdk.json
- project.json
- tsconfig.* mises à jour des références
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)],});
new ApplicationStack(app, 'dungeon-adventure-infra-sandbox', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION, }, crossRegionReferences: true,});
app.synth();
Ce point d’entrée utilise cfn-guard
pour valider l’infrastructure.
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);
// Implémentation des ressources CDK }}
C’est ici que nous instancierons nos constructions CDK.
Mise à jour de l’infrastructure
Section intitulée « Mise à jour de l’infrastructure »Modifions packages/infra/src/stacks/application-stack.ts
pour instancier nos constructions :
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);
// The code that defines your stack goes here const userIdentity = new UserIdentity(this, 'UserIdentity');
const gameApi = new GameApi(this, 'GameApi', { integrations: GameApi.defaultIntegrations(this).build(), }); const storyApi = new StoryApi(this, 'StoryApi', { integrations: StoryApi.defaultIntegrations(this).build(), });
// grant our authenticated role access to invoke our APIs [storyApi, gameApi].forEach((api) => api.grantInvokeAccess(userIdentity.identityPool.authenticatedRole), );
// Ensure this is instantiated last so our runtime-config.json can be automatically configured new GameUI(this, 'GameUI'); }}
Nous utilisons les intégrations par défaut pour nos APIs, chaque opération étant mappée à une fonction Lambda.
Construction du code
Section intitulée « Construction du code »Commandes Nx
Cibles uniques vs multiples
Section intitulée « Cibles uniques vs multiples »La commande run-many
exécute une cible sur plusieurs sous-projets. Les dépendances sont respectées.
Pour une cible unique :
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
Visualisation des dépendances
Section intitulée « Visualisation des dépendances »Visualisez les dépendances avec :
pnpm nx graph
yarn nx graph
npx nx graph
bunx nx graph

Nx utilise le cache pour accélérer les builds. Utilisez --skip-nx-cache
pour l’ignorer :
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
Effacez le cache avec :
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
Vous devriez voir :
NX The workspace is out of sync
[@nx/js:typescript-sync]: Certains fichiers de configuration TypeScript manquent des références de projet.
? Souhaitez-vous synchroniser les modifications pour mettre à jour l'espace de travail ? …Oui, synchroniser et exécuter les tâchesNon, exécuter sans synchroniser
Sélectionnez Oui pour résoudre les erreurs d’import dans votre IDE.
Les artefacts sont générés dans dist/
. Félicitations, vous avez créé tous les sous-projets nécessaires ! 🎉🎉🎉