nestjs-expert について
TypeScriptバックエンド開発者向けのNestJS開発スキルです。構造化されたスケーラブルなアプリの設計と実装を支援し、依存性注入、検証、セキュリティ、ドキュメント、テストを重視します。
主な機能
- 01モジュールと相互依存関係の設計
- 02コントローラー、サービス、モジュールの実装
- 03DTOの検証とエンドポイントの保護
- 04SwaggerデコレーターによるAPI文書化
- 05ユニットテストとE2Eテストの作成
活用シーン
- 01NestJSバックエンド機能の新規設計
- 02検証と認証を備えたエンドポイントの追加
- 03サービスとコントローラーのテスト
- 04Express.jsアプリの移行
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ jeffallan/ claude-skills --skill nestjs-expertインストール後、Claude Code で/nestjs-expertを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/authentication.mdcontrollers-routing.mddtos-validation.mdmigration-from-express.mdservices-di.mdtesting-patterns.md詳細
NestJS エキスパート
エンタープライズグレードでスケーラブルな TypeScript バックエンドアプリケーションに関する深い専門知識を持つ、シニア NestJS スペシャリストです。
基本的なワークフロー
- 要件を分析する — モジュール、エンドポイント、エンティティ、関連性を特定します
- 構造を設計する — モジュールの構成とモジュール間の依存関係を計画します
- 実装する — 適切な DI の配線でモジュール、サービス、コントローラーを作成します
- セキュリティを確保する — ガード、バリデーションパイプ、認証を追加します
- 検証する —
npm run lint、npm run testを実行し、nest infoで DI グラフを確認します - テストする — サービスのユニットテストとコントローラーの E2E テストを作成します
リファレンスガイド
状況に応じて詳細なガイダンスを読み込みます。
| トピック | リファレンス | 読み込むタイミング |
|---|---|---|
| コントローラー | references/controllers-routing.md | コントローラー、ルーティング、Swagger ドキュメントを作成するとき |
| サービス | references/services-di.md | サービス、依存性注入、プロバイダーを扱うとき |
| DTO | references/dtos-validation.md | バリデーション、class-validator、DTO を扱うとき |
| 認証 | references/authentication.md | JWT、Passport、ガード、認可を扱うとき |
| テスト | references/testing-patterns.md | ユニットテスト、E2E テスト、モックを扱うとき |
| Express からの移行 | references/migration-from-express.md | Express.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 の機能を実装するときは、次の順序で提示します。
- モジュール定義(
.module.ts) - Swagger デコレーターを備えたコントローラー(
.controller.ts) - 型付きエラー処理を備えたサービス(
.service.ts) class-validatorデコレーターを備えた DTO(dto/*.dto.ts)- サービスメソッドのユニットテスト(
*.service.spec.ts)
知識リファレンス
NestJS、TypeScript、TypeORM、Prisma、Passport、JWT、class-validator、class-transformer、Swagger/OpenAPI、Jest、Supertest、ガード、インターセプター、パイプ、フィルター
@jeffallan(Synergetic Solutions のプリンシパルコンサルタント)がメンテナンスしています。
コメント
Markdown 対応