ジェネレーターを作成する
@aws/nx-plugin向けの新しいジェネレータを作成して、tRPC APIの新しいプロシージャを生成できるようにしましょう。
プラグインのチェックアウト
Section titled “プラグインのチェックアウト”まずプラグインをクローンします:
git clone git@github.com:awslabs/nx-plugin-for-aws.git依存関係のインストールとビルド:
cd nx-plugin-for-awspnpm ipnpm nx run-many --target build --all空のジェネレータ作成
Section titled “空のジェネレータ作成”新しいジェネレータを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 APIyarn 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 APInpx 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 APIbunx 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-runyarn 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-runnpx 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-runbunx 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以下のファイルが自動生成されます:
Directorypackages/nx-plugin/src/trpc/procedure
- schema.json ジェネレータの入力スキーマ定義
- schema.d.ts スキーマに対応するTypeScriptインターフェース
- generator.ts ジェネレータの実装
- generator.spec.ts テストコード
Directorydocs/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プロジェクト", "x-prompt": "プロシージャを追加するtRPC APIプロジェクトを選択", "x-dropdown": "projects", "x-priority": "important" }, "procedure": { "description": "新規プロシージャ名", "type": "string", "x-prompt": "新規プロシージャの名前を入力", "x-priority": "important", }, "type": { "description": "生成するプロシージャのタイプ", "type": "string", "x-prompt": "プロシージャタイプを選択", "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" } },...ジェネレータの実装
Section titled “ジェネレータの実装”tRPC APIにプロシージャを追加するには2つの作業が必要です:
- 新規プロシージャ用TypeScriptファイルの作成
- ルーターへのプロシージャ登録
新規プロシージャの作成
Section titled “新規プロシージャの作成”generateFilesユーティリティを使用してEJSテンプレートをレンダリングします。テンプレートはpackages/nx-plugin/src/trpc/procedure/files/procedures/__procedureNameKebabCase__.ts.templateに作成します:
import { publicProcedure } from '../init.js';import { z } from 'zod';
export const <%- procedureNameCamelCase %> = publicProcedure .input(z.object({ // TODO: 入力定義 })) .output(z.object({ // TODO: 出力定義 })) .<%- procedureType %>(async ({ input, ctx }) => { // TODO: 実装 return {}; });テンプレートで使用する3つの変数:
procedureNameCamelCaseprocedureNameKebabCaseprocedureType
これらをgenerateFilesに渡す必要があります。ユーザーが選択したプロジェクトのソースルートはプロジェクト設定から取得します。
ジェネレータを更新:
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;ルーターへのプロシージャ登録
Section titled “ルーターへのプロシージャ登録”TypeScript AST操作でソースコードを更新します。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ジェネレータのテスト
Section titled “ジェネレータのテスト”ローカルのNx Plugin for AWSを既存プロジェクトにリンクしてテストします。
tRPC APIプロジェクトの作成
Section titled “tRPC APIプロジェクトの作成”別ディレクトリでテスト用ワークスペースを作成:
npx create-nx-workspace@21.6.8 trpc-generator-test --pm=pnpm --preset=@aws/nx-plugin --ci=skip --aiAgentsnpx create-nx-workspace@21.6.8 trpc-generator-test --pm=yarn --preset=@aws/nx-plugin --ci=skip --aiAgentsnpx create-nx-workspace@21.6.8 trpc-generator-test --pm=npm --preset=@aws/nx-plugin --ci=skip --aiAgentsnpx create-nx-workspace@21.6.8 trpc-generator-test --pm=bun --preset=@aws/nx-plugin --ci=skip --aiAgentstRPC 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-interactiveyarn nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactivenpx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactivebunx 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-runyarn nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-runnpx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-runbunx nx g @aws/nx-plugin:ts#trpc-api --apiName=test-api --no-interactive --dry-runローカルプラグインのリンク
Section titled “ローカルプラグインのリンク”@aws/nx-pluginをリンク:
cd path/to/trpc-generator-testpnpm link path/to/nx-plugin-for-aws/dist/packages/nx-plugincd path/to/trpc-generator-testyarn link path/to/nx-plugin-for-aws/dist/packages/nx-plugincd path/to/trpc-generator-testnpm link path/to/nx-plugin-for-aws/dist/packages/nx-plugincd path/to/nx-plugin-for-aws/dist/packages/nx-pluginbun linkcd path/to/trpc-generator-testbun link @aws/nx-pluginジェネレータの実行
Section titled “ジェネレータの実行”新規ジェネレータを実行:
- インストール 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#procedureyarn nx g @aws/nx-plugin:ts#trpc-api#procedurenpx nx g @aws/nx-plugin:ts#trpc-api#procedurebunx nx g @aws/nx-plugin:ts#trpc-api#procedure変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-runyarn nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-runnpx nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-runbunx nx g @aws/nx-plugin:ts#trpc-api#procedure --dry-run成功すると、新しいプロシージャが生成されrouter.tsに追加されます。
さらにNxジェネレータの理解を深めるための拡張案:
1. ネスト化操作
Section titled “1. ネスト化操作”ドット表記のprocedure入力(例: games.query)をサポートするようジェネレータを拡張:
- 逆ドット表記のプロシージャ名生成(例:
queryGames) - 適切なネスト化ルーターの生成/更新
2. バリデーション
Section titled “2. バリデーション”tRPC APIでないプロジェクトが選択された場合の防御処理を追加。api-connectionジェネレータを参考に実装。
3. ユニットテスト
Section titled “3. ユニットテスト”ジェネレータのユニットテスト実装。基本的な流れ:
createTreeUsingTsSolutionSetup()で空ワークスペース作成- 既存ファイル(
project.jsonやsrc/router.ts)をツリーに追加 - テスト対象ジェネレータ実行
- 期待通りの変更が行われたか検証
4. E2Eテスト
Section titled “4. E2Eテスト”現在の「smoke test」に新規ジェネレータを含めるよう更新。