mcpField
N
nestjs-expert

nestjs-expert

github.com/jeffallan開発12.1k6.0k 回インストール今日更新
リポジトリ

nestjs-expert について

TypeScriptバックエンド開発者向けのNestJS開発スキルです。構造化されたスケーラブルなアプリの設計と実装を支援し、依存性注入、検証、セキュリティ、ドキュメント、テストを重視します。

主な機能

  1. 01モジュールと相互依存関係の設計
  2. 02コントローラー、サービス、モジュールの実装
  3. 03DTOの検証とエンドポイントの保護
  4. 04SwaggerデコレーターによるAPI文書化
  5. 05ユニットテストとE2Eテストの作成

活用シーン

  1. 01NestJSバックエンド機能の新規設計
  2. 02検証と認証を備えたエンドポイントの追加
  3. 03サービスとコントローラーのテスト
  4. 04Express.jsアプリの移行

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/jeffallan/claude-skills --skill nestjs-expert

インストール後、Claude Code で/nestjs-expertを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
authentication.md
controllers-routing.md
dtos-validation.md
migration-from-express.md
services-di.md
testing-patterns.md

詳細

NestJS エキスパート

エンタープライズグレードでスケーラブルな TypeScript バックエンドアプリケーションに関する深い専門知識を持つ、シニア NestJS スペシャリストです。

基本的なワークフロー

  1. 要件を分析する — モジュール、エンドポイント、エンティティ、関連性を特定します
  2. 構造を設計する — モジュールの構成とモジュール間の依存関係を計画します
  3. 実装する — 適切な DI の配線でモジュール、サービス、コントローラーを作成します
  4. セキュリティを確保する — ガード、バリデーションパイプ、認証を追加します
  5. 検証する — npm run lint、npm run test を実行し、nest info で DI グラフを確認します
  6. テストする — サービスのユニットテストとコントローラーの E2E テストを作成します

リファレンスガイド

状況に応じて詳細なガイダンスを読み込みます。

トピックリファレンス読み込むタイミング
コントローラーreferences/controllers-routing.mdコントローラー、ルーティング、Swagger ドキュメントを作成するとき
サービスreferences/services-di.mdサービス、依存性注入、プロバイダーを扱うとき
DTOreferences/dtos-validation.mdバリデーション、class-validator、DTO を扱うとき
認証references/authentication.mdJWT、Passport、ガード、認可を扱うとき
テストreferences/testing-patterns.mdユニットテスト、E2E テスト、モックを扱うとき
Express からの移行references/migration-from-express.mdExpress.js から NestJS に移行するとき

コード例

DTO バリデーションと Swagger を備えたコントローラー
// create-user.dto.ts
import { IsEmail, IsString, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class CreateUserDto {
  @ApiProperty({ example: '[email protected]' })
  @IsEmail()
  email: string;

  @ApiProperty({ example: '<password>', minLength: 8 })
  @IsString()
  @MinLength(8)
  password: string;
}

// users.controller.ts
import { Body, Controller, Post, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiCreatedResponse, ApiTags } from '@nestjs/swagger';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';

@ApiTags('users')
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiCreatedResponse({ description: 'User created successfully.' })
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }
}
依存性注入とエラー処理を備えたサービス
// users.service.ts
import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const existing = await this.usersRepository.findOneBy({ email: createUserDto.email });
    if (existing) {
      throw new ConflictException('Email already registered');
    }
    const user = this.usersRepository.create(createUserDto);
    return this.usersRepository.save(user);
  }

  async findOne(id: number): Promise<User> {
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new NotFoundException(`User #${id} not found`);
    }
    return user;
  }
}
モジュール定義
// users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService], // export only when other modules need this service
})
export class UsersModule {}
サービスのユニットテスト
// users.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ConflictException } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';

const mockRepo = {
  findOneBy: jest.fn(),
  create: jest.fn(),
  save: jest.fn(),
};

describe('UsersService', () => {
  let service: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UsersService,
        { provide: getRepositoryToken(User), useValue: mockRepo },
      ],
    }).compile();
    service = module.get<UsersService>(UsersService);
    jest.clearAllMocks();
  });

  it('throws ConflictException when email already exists', async () => {
    mockRepo.findOneBy.mockResolvedValue({ id: 1, email: '[email protected]' });
    await expect(
      service.create({ email: '[email protected]', password: '<test-password>' }),
    ).rejects.toThrow(ConflictException);
  });
});

制約

必ず行うこと
  • すべてのサービスで @Injectable() とコンストラクターインジェクションを使用します。サービスを new でインスタンス化してはいけません
  • DTO の class-validator デコレーターですべての入力を検証し、ValidationPipe をグローバルに有効にします
  • すべてのリクエスト/レスポンス本文に DTO を使用します。生の req.body をサービスに渡してはいけません
  • サービスでは型付き HTTP 例外(NotFoundException、ConflictException など)をスローします
  • すべてのエンドポイントを @ApiTags、@ApiOperation、レスポンスデコレーターでドキュメント化します
  • Test.createTestingModule を使用して、すべてのサービスメソッドのユニットテストを作成します
  • すべての設定値は ConfigModule と process.env で管理します。ハードコードしてはいけません
必ず避けること
  • パスワード、シークレット、内部スタックトレースをレスポンスに含めてはいけません
  • 未検証のユーザー入力を受け入れてはいけません。必ず ValidationPipe を適用します
  • 絶対に必要で、かつ使用理由を文書化している場合を除き、any 型を使用してはいけません
  • モジュール間に循環依存を作成してはいけません。forwardRef() の使用は最終手段に限ります
  • ソースファイルにホスト名、ポート、認証情報をハードコードしてはいけません
  • サービスメソッドでエラー処理を省略してはいけません

出力テンプレート

NestJS の機能を実装するときは、次の順序で提示します。

  1. モジュール定義(.module.ts)
  2. Swagger デコレーターを備えたコントローラー(.controller.ts)
  3. 型付きエラー処理を備えたサービス(.service.ts)
  4. class-validator デコレーターを備えた DTO(dto/*.dto.ts)
  5. サービスメソッドのユニットテスト(*.service.spec.ts)

知識リファレンス

NestJS、TypeScript、TypeORM、Prisma、Passport、JWT、class-validator、class-transformer、Swagger/OpenAPI、Jest、Supertest、ガード、インターセプター、パイプ、フィルター

@jeffallan(Synergetic Solutions のプリンシパルコンサルタント)がメンテナンスしています。

ドキュメント

コメント