생성기 기여하기
@aws/nx-plugin
에 기여할 새로운 제너레이터를 생성해 보겠습니다. 목표는 tRPC API를 위한 새로운 프로시저를 생성하는 것입니다.
플러그인 확인
섹션 제목: “플러그인 확인”먼저 플러그인을 클론합니다:
git clone git@github.com:awslabs/nx-plugin-for-aws.git
그 다음 설치 및 빌드:
cd nx-plugin-for-awspnpm ipnpm nx run-many --target build --all
빈 제너레이터 생성
섹션 제목: “빈 제너레이터 생성”새 제너레이터를 packages/nx-plugin/src/trpc/procedure
에 생성합니다.
새 제너레이터를 빠르게 스캐폴딩할 수 있도록 제너레이터 생성용 제너레이터가 제공됩니다! 다음 명령으로 실행할 수 있습니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#nx-generator
- 필수 매개변수 입력
- pluginProject: @aws/nx-plugin
- name: ts#trpc-api#procedure
- directory: trpc/procedure
- description: Adds a procedure to a tRPC API
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API
yarn nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API
npx nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API
bunx nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API --dry-run
yarn nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API --dry-run
npx nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API --dry-run
bunx nx g @aws/nx-plugin:ts#nx-generator --pluginProject=@aws/nx-plugin --name=ts#trpc-api#procedure --directory=trpc/procedure --description=Adds a procedure to a tRPC API --dry-run
다음 파일들이 생성된 것을 확인할 수 있습니다:
디렉터리packages/nx-plugin/src/trpc/procedure
- schema.json 제너레이터 입력 정의
- schema.d.ts 스키마와 일치하는 타입스크립트 인터페이스
- generator.ts Nx가 실행하는 제너레이터 함수
- generator.spec.ts 제너레이터 테스트
디렉터리docs/src/content/docs/guides/
- trpc-procedure.mdx 제너레이터 문서
- packages/nx-plugin/generators.json 제너레이터 포함되도록 업데이트됨
제너레이터에 필요한 속성을 추가하기 위해 스키마를 업데이트합니다:
{ "$schema": "https://json-schema.org/schema", "$id": "tRPCProcedure", "title": "Adds a procedure to a tRPC API", "type": "object", "properties": { "project": { "type": "string", "description": "tRPC API project", "x-prompt": "Select the tRPC API project to add the procedure to", "x-dropdown": "projects", "x-priority": "important" }, "procedure": { "description": "The name of the new procedure", "type": "string", "x-prompt": "What would you like to call your new procedure?", "x-priority": "important", }, "type": { "description": "The type of procedure to generate", "type": "string", "x-prompt": "What type of procedure would you like to generate?", "x-priority": "important", "default": "query", "enum": ["query", "mutation"] } }, "required": ["project", "procedure"]}
export interface TrpcProcedureSchema { project: string; procedure: string; type: 'query' | 'mutation';}
packages/nx-plugin/generators.json
에 제너레이터가 이미 연결된 것을 확인할 수 있습니다:
... "generators": { ... "ts#trpc-api#procedure": { "factory": "./src/trpc/procedure/generator", "schema": "./src/trpc/procedure/schema.json", "description": "Adds a procedure to a tRPC API" } },...
제너레이터 구현
섹션 제목: “제너레이터 구현”tRPC API에 프로시저를 추가하려면 두 가지가 필요합니다:
- 새 프로시저용 TypeScript 파일 생성
- 라우터에 프로시저 추가
새 프로시저 생성
섹션 제목: “새 프로시저 생성”새 프로시저용 TypeScript 파일을 생성하기 위해 generateFiles
유틸리티를 사용합니다. 이를 통해 사용자가 선택한 옵션을 기반으로 변수를 렌더링할 수 있는 EJS 템플릿을 정의할 수 있습니다.
먼저 packages/nx-plugin/src/trpc/procedure/files/procedures/__procedureNameKebabCase__.ts.template
에 템플릿을 정의합니다:
import { publicProcedure } from '../init.js';import { z } from 'zod/v4';
export const <%- procedureNameCamelCase %> = publicProcedure .input(z.object({ // TODO: define input })) .output(z.object({ // TODO: define output })) .<%- procedureType %>(async ({ input, ctx }) => { // TODO: implement! return {}; });
템플릿에서 세 가지 변수를 참조했습니다:
procedureNameCamelCase
procedureNameKebabCase
procedureType
이 변수들을 generateFiles
에 전달해야 하며, 사용자가 제너레이터 입력으로 선택한 tRPC 프로젝트의 소스 파일 위치(즉, sourceRoot
)를 프로젝트 구성에서 추출할 수 있습니다.
제너레이터를 업데이트하여 이를 수행합니다:
import { generateFiles, joinPathFragments, readProjectConfiguration, Tree,} from '@nx/devkit';import { TrpcProcedureSchema } from './schema';import { formatFilesInSubtree } from '../../utils/format';import camelCase from 'lodash.camelcase';import kebabCase from 'lodash.kebabcase';
export const trpcProcedureGenerator = async ( tree: Tree, options: TrpcProcedureSchema,) => { const projectConfig = readProjectConfiguration(tree, options.project);
const procedureNameCamelCase = camelCase(options.procedure); const procedureNameKebabCase = kebabCase(options.procedure);
generateFiles( tree, joinPathFragments(__dirname, 'files'), projectConfig.sourceRoot, { procedureNameCamelCase, procedureNameKebabCase, procedureType: options.type, }, );
await formatFilesInSubtree(tree);};
export default trpcProcedureGenerator;
라우터에 프로시저 추가
섹션 제목: “라우터에 프로시저 추가”다음으로 제너레이터가 새 프로시저를 라우터에 연결하도록 합니다. 이는 사용자의 소스 코드를 읽고 수정해야 함을 의미합니다!
TypeScript AST 조작을 사용하여 TypeScript 소스 파일의 관련 부분을 업데이트합니다. replace
와 destructuredImport
헬퍼를 사용하여 이를 더 쉽게 수행할 수 있습니다.
import { generateFiles, joinPathFragments, readProjectConfiguration, Tree,} from '@nx/devkit';import { TrpcProcedureSchema } from './schema';import { formatFilesInSubtree } from '../../utils/format';import camelCase from 'lodash.camelcase';import kebabCase from 'lodash.kebabcase';import { destructuredImport, replace } from '../../utils/ast';import { factory, ObjectLiteralExpression } from 'typescript';
export const trpcProcedureGenerator = async ( tree: Tree, options: TrpcProcedureSchema,) => { const projectConfig = readProjectConfiguration(tree, options.project);
const procedureNameCamelCase = camelCase(options.procedure); const procedureNameKebabCase = kebabCase(options.procedure);
generateFiles( tree, joinPathFragments(__dirname, 'files'), projectConfig.sourceRoot, { procedureNameCamelCase, procedureNameKebabCase, procedureType: options.type, }, );
const routerPath = joinPathFragments(projectConfig.sourceRoot, 'router.ts');
destructuredImport( tree, routerPath, [procedureNameCamelCase], `./procedures/${procedureNameKebabCase}.js`, );
replace( tree, routerPath, 'CallExpression[expression.name="router"] > ObjectLiteralExpression', (node) => factory.createObjectLiteralExpression([ ...(node as ObjectLiteralExpression).properties, factory.createShorthandPropertyAssignment(procedureNameCamelCase), ]), );
await formatFilesInSubtree(tree);};
export default trpcProcedureGenerator;
이제 제너레이터를 구현했으므로 던전 어드벤처 프로젝트에서 테스트할 수 있도록 컴파일합니다.
pnpm nx run @aws/nx-plugin:compile
제너레이터 테스트
섹션 제목: “제너레이터 테스트”제너레이터를 테스트하기 위해 로컬 Nx Plugin for AWS를 기존 코드베이스에 연결합니다.
tRPC API가 있는 테스트 프로젝트 생성
섹션 제목: “tRPC API가 있는 테스트 프로젝트 생성”별도 디렉토리에서 새 테스트 워크스페이스 생성:
npx create-nx-workspace@~21.0.3 trpc-generator-test --pm=pnpm --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 trpc-generator-test --pm=yarn --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 trpc-generator-test --pm=npm --preset=@aws/nx-plugin --ci=skip
npx create-nx-workspace@~21.0.3 trpc-generator-test --pm=bun --preset=@aws/nx-plugin --ci=skip
다음으로 프로시저를 추가할 tRPC API 생성:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#trpc-api
- 필수 매개변수 입력
- apiName: test-api
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive
yarn nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive
npx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive
bunx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-run
yarn nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-run
npx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-run
bunx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-run
로컬 Nx Plugin for AWS 연결
섹션 제목: “로컬 Nx Plugin for AWS 연결”코드베이스에서 로컬 @aws/nx-plugin
연결:
cd path/to/trpc-generator-testpnpm link path/to/nx-plugin-for-aws/dist/packages/nx-plugin
cd path/to/trpc-generator-testyarn link path/to/nx-plugin-for-aws/dist/packages/nx-plugin
cd path/to/trpc-generator-testnpm link path/to/nx-plugin-for-aws/dist/packages/nx-plugin
cd path/to/nx-plugin-for-aws/dist/packages/nx-pluginbun linkcd path/to/trpc-generator-testbun link @aws/nx-plugin
새 제너레이터 실행
섹션 제목: “새 제너레이터 실행”새 제너레이터 실행 시도:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#trpc-api#procedure
- 필수 매개변수 입력
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#trpc-api#procedure
yarn nx g @aws/nx-plugin:ts#trpc-api#procedure
npx nx g @aws/nx-plugin:ts#trpc-api#procedure
bunx nx g @aws/nx-plugin:ts#trpc-api#procedure
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-run
yarn nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-run
npx nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-run
bunx nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-run
성공했다면 새 프로시저가 생성되고 router.ts
에 프로시저가 추가되었을 것입니다.
연습 문제
섹션 제목: “연습 문제”여기까지 진행했고 Nx 제너레이터를 실험할 시간이 남았다면 프로시저 제너레이터에 추가할 기능 제안:
1. 중첩 연산
섹션 제목: “1. 중첩 연산”제너레이터를 업데이트하여 중첩 라우터 지원:
procedure
입력에 점 표기법 허용 (예:games.query
)- 역점 표기법 기반 이름의 프로시저 생성 (예:
queryGames
) - 적절한 중첩 라우터 추가 (이미 존재한다면 업데이트)
2. 유효성 검사
섹션 제목: “2. 유효성 검사”제너레이터는 tRPC API가 아닌 project
선택과 같은 잠재적 문제를 방어해야 합니다. api-connection
제너레이터 예제를 참고하세요.
3. 단위 테스트
섹션 제목: “3. 단위 테스트”제너레이터용 단위 테스트 작성. 일반적인 흐름은 다음과 같습니다:
createTreeUsingTsSolutionSetup()
로 빈 워크스페이스 트리 생성- 트리에 이미 존재해야 하는 파일 추가 (예: tRPC 백엔드용
project.json
및src/router.ts
) - 테스트 대상 제너레이터 실행
- 트리에 예상 변경 사항이 적용되었는지 검증
4. 종단 간 테스트
섹션 제목: “4. 종단 간 테스트”현재 모든 제너레이터를 실행하고 빌드 성공을 확인하는 단일 “스모크 테스트”가 있습니다. 새 제너레이터를 포함하도록 업데이트해야 합니다.