Nestjsのロゴ

Nestjs

コミュニティ
Omar-Obando
nestjs

NestJS TypeScript framework development patterns — modular architecture with controllers/providers/exports, Guards for authentication (global via APP_GUARD), Pipes for validation, Interceptors for transforms, request lifecycle management, CLI schematics for code generation, and enterprise-grade patterns.

概要

公開者Omar-Obando
リポジトリqwen-orchestrator
スキル名nestjs
スター
53
フォーク
13
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    Omar-ObandoがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルNestjsをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/Omar-Obando/qwen-orchestrator/tree/main/skills/nestjs
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Omar-Obando/qwen-orchestrator.git /tmp/qwen-orchestrator
mkdir -p .claude/skills
cp -r /tmp/qwen-orchestrator/skills/nestjs .claude/skills/nestjs
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでNestjsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にNestjsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Nestjsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

NestJS Development Skill — Enterprise TypeScript Framework

This skill provides comprehensive NestJS development patterns for building scalable, testable, enterprise-grade Node.js applications with modular architecture and decorator-driven design.

Key Principles

  • Modular Architecture: Organize code into feature modules with clear boundaries
  • Dependency Injection: Let the container resolve and inject dependencies
  • Decorator-Driven: Use decorators for metadata-driven behavior (routes, validation, guards)
  • Separation of Concerns: Controllers handle HTTP, Services handle logic, Modules wire it together

Module Structure

Feature Module

typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProductsController } from './products.controller';
import { ProductsService } from './products.service';
import { Product } from './entities/product.entity';
import { ProductRepository } from './repositories/product.repository';

@Module({
  imports: [TypeOrmModule.forFeature([Product])],
  controllers: [ProductsController],
  providers: [ProductsService, ProductRepository],
  exports: [ProductsService],
})
export class ProductsModule {}

Module Types

TypePurposeExample
Feature ModuleGroup related featuresProductsModule
Shared ModuleReusable across featuresDatabaseModule, LoggerModule
Global ModuleAvailable everywhereConfigModule, AuthModule
Dynamic ModuleConfigurable at registrationTypeOrmModule.forRootAsync()

Shared Module Pattern

typescript
@Module({
  providers: [LoggerService, DateService],
  exports: [LoggerService, DateService],
})
export class SharedModule {}

// Used in feature modules
@Module({
  imports: [SharedModule],
  // LoggerService and DateService now available for injection
})
export class OrdersModule {}

Global Module

typescript
import { Global, Module } from '@nestjs/common';

@Global()
@Module({
  providers: [ConfigService],
  exports: [ConfigService],
})
export class ConfigModule {}
// ConfigService available everywhere without importing

Controllers

REST Controller

typescript
import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Patch,
  Param,
  Body,
  Query,
  HttpCode,
  HttpStatus,
  Res,
} from '@nestjs/common';
import { ProductsService } from './products.service';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { PaginationQueryDto } from '../common/dto/pagination-query.dto';

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() dto: CreateProductDto) {
    return this.productsService.create(dto);
  }

  @Get()
  findAll(@Query() query: PaginationQueryDto) {
    return this.productsService.findAll(query);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.productsService.findOne(id);
  }

  @Put(':id')
  update(@Param('id') id: string, @Body() dto: UpdateProductDto) {
    return this.productsService.update(id, dto);
  }

  @Patch(':id')
  partialUpdate(
    @Param('id') id: string,
    @Body() dto: Partial<UpdateProductDto>
  ) {
    return this.productsService.partialUpdate(id, dto);
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string) {
    return this.productsService.remove(id);
  }
}

DTOs with Validation

typescript
import {
  IsString,
  IsNumber,
  IsOptional,
  IsBoolean,
  IsArray,
  Min,
  Max,
  MaxLength,
  IsUUID,
} from 'class-validator';
import { Type } from 'class-transformer';

export class CreateProductDto {
  @IsString()
  @MaxLength(255)
  name: string;

  @IsString()
  @IsUUID()
  categoryId: string;

  @IsNumber({ maxDecimalPlaces: 2 })
  @Min(0)
  @Max(999999.99)
  @Type(() => Number)
  price: number;

  @IsOptional()
  @IsString()
  @MaxLength(5000)
  description?: string;

  @IsOptional()
  @IsBoolean()
  isActive?: boolean;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  tags?: string[];
}

export class PaginationQueryDto {
  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  page?: number = 1;

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  @Max(100)
  limit?: number = 20;

  @IsOptional()
  @IsString()
  sort?: string = 'createdAt:DESC';
}

Providers (Services)

Injectable Service

typescript
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './entities/product.entity';
import { CreateProductDto } from './dto/create-product.dto';

@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepo: Repository<Product>
  ) {}

  async create(dto: CreateProductDto): Promise<Product> {
    const product = this.productRepo.create(dto);
    return this.productRepo.save(product);
  }

  async findAll(query: PaginationQueryDto): Promise<[Product[], number]> {
    const { page, limit, sort } = query;
    const [field, order] = sort.split(':');

    return this.productRepo.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { [field]: order === 'ASC' ? 'ASC' : 'DESC' },
      relations: ['category'],
    });
  }

  async findOne(id: string): Promise<Product> {
    const product = await this.productRepo.findOne({
      where: { id },
      relations: ['category', 'reviews'],
    });
    if (!product) {
      throw new NotFoundException(`Product ${id} not found`);
    }
    return product;
  }

  async update(id: string, dto: UpdateProductDto): Promise<Product> {
    const product = await this.findOne(id);
    Object.assign(product, dto);
    return this.productRepo.save(product);
  }

  async remove(id: string): Promise<void> {
    const result = await this.productRepo.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`Product ${id} not found`);
    }
  }
}

Custom and Factory Providers

typescript
// Factory provider
{
  provide: 'CONFIG',
  useFactory: (envService: EnvService) => {
    return envService.getConfig();
  },
  inject: [EnvService],
}

// Async factory provider
{
  provide: 'DATABASE_CONNECTION',
  useFactory: async (configService: ConfigService) => {
    const connection = await createConnection({
      host: configService.get('DB_HOST'),
      port: configService.get('DB_PORT'),
    });
    return connection;
  },
  inject: [ConfigService],
}

// Value provider
{
  provide: 'API_VERSION',
  useValue: 'v1',
}

Guards (Authentication & Authorization)

JWT Auth Guard (Global)

typescript
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<Request>();
    const token = this.extractToken(request);

    if (!token) {
      throw new UnauthorizedException('Missing authentication token');
    }

    try {
      const payload = await this.jwtService.verifyAsync(token);
      request['user'] = payload;
    } catch {
      throw new UnauthorizedException('Invalid or expired token');
    }

    return true;
  }

  private extractToken(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}

Role-Based Guard

typescript
import { Reflector } from '@nestjs/core';
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';

export const ROLES_KEY = 'roles';

export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles) return true;

    const { user } = context.switchToHttp().getRequest();

    const hasRole = requiredRoles.some((role) => user.roles?.includes(role));
    if (!hasRole) {
      throw new ForbiddenException('Insufficient permissions');
    }

    return true;
  }
}

// Register globally
@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
  ],
})
export class AuthModule {}

// Usage in controller
@Roles('admin')
@Delete(':id')
remove(@Param('id') id: string) {
  return this.productsService.remove(id);
}

Pipes (Validation & Transformation)

Global Validation Pipe

typescript
// main.ts
import { ValidationPipe } from '@nestjs/common';

app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true, // Strip unknown properties
    forbidNonWhitelisted: true, // Throw error on unknown properties
    transform: true, // Auto-transform types (string → number)
    transformOptions: {
      enableImplicitConversion: true,
    },
    disableErrorMessages: false,
  })
);

Custom Pipe

typescript
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
  transform(value: string): number {
    const parsed = parseInt(value, 10);
    if (isNaN(parsed)) {
      throw new BadRequestException(`"${value}" is not a valid number`);
    }
    return parsed;
  }
}

Interceptors

Logging Interceptor

typescript
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const { method, url } = request;
    const startTime = Date.now();

    return next.handle().pipe(
      tap(() => {
        const duration = Date.now() - startTime;
        this.logger.log(`${method} ${url} — ${duration}ms`);
      })
    );
  }
}

Transform Interceptor

typescript
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';

export interface ApiResponse<T> {
  success: true;
  data: T;
  timestamp: string;
}

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<
  T,
  ApiResponse<T>
> {
  intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Observable<ApiResponse<T>> {
    return next.handle().pipe(
      map((data) => ({
        success: true as const,
        data,
        timestamp: new Date().toISOString(),
      }))
    );
  }
}

Request Lifecycle

Understanding the order of execution is critical:

Incoming Request
    │
    ├── 1. Middleware (module-level, then global)
    ├── 2. Guard (global, then controller, then route)
    ├── 3. Interceptor (before) — global, then controller, then route
    ├── 4. Pipe (global, then parameter-level)
    ├── 5. Controller Method
    ├── 6. Service (business logic)
    ├── 7. Interceptor (after) — route, then controller, then global
    └── 8. Exception Filter (if any error occurred)

CLI Schematics

Code Generation Commands

bash
nest g module products          # Generate module
nest g controller products      # Generate controller
nest g service products         # Generate service
nest g guard auth               # Generate guard
nest g interceptor logging      # Generate interceptor
nest g pipe validate            # Generate pipe
nest g filter http-exception    # Generate exception filter
nest g resource products        # Generate full CRUD module
nest g decorator roles          # Generate custom decorator
nest g middleware logger        # Generate middleware

Resource Generator (Full CRUD)

bash
nest g resource products
# Creates:
#   products/
#   ├── dto/
#   │   ├── create-product.dto.ts
#   │   └── update-product.dto.ts
#   ├── entities/
#   │   └── product.entity.ts
#   ├── products.module.ts
#   ├── products.controller.ts
#   ├── products.controller.spec.ts
#   ├── products.service.ts
#   └── products.service.spec.ts

Testing

Unit Testing with Jest

typescript
import { Test, TestingModule } from '@nestjs/testing';
import { ProductsService } from './products.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Product } from './entities/product.entity';
import { NotFoundException } from '@nestjs/common';

describe('ProductsService', () => {
  let service: ProductsService;
  let mockRepo: any;

  beforeEach(async () => {
    mockRepo = {
      find: jest.fn(),
      findOne: jest.fn(),
      create: jest.fn(),
      save: jest.fn(),
      delete: jest.fn(),
    };

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ProductsService,
        {
          provide: getRepositoryToken(Product),
          useValue: mockRepo,
        },
      ],
    }).compile();

    service = module.get<ProductsService>(ProductsService);
  });

  it('should return a product by id', async () => {
    const product = { id: '1', name: 'Test' };
    mockRepo.findOne.mockResolvedValue(product);

    const result = await service.findOne('1');
    expect(result).toEqual(product);
    expect(mockRepo.findOne).toHaveBeenCalledWith({
      where: { id: '1' },
      relations: ['category', 'reviews'],
    });
  });

  it('should throw NotFoundException for missing product', async () => {
    mockRepo.findOne.mockResolvedValue(null);

    await expect(service.findOne('999')).rejects.toThrow(NotFoundException);
  });
});

E2E Testing

typescript
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { AppModule } from '../app.module';
import { INestApplication, ValidationPipe } from '@nestjs/common';

describe('Products (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
    await app.init();
  });

  it('POST /products — should create a product', () => {
    return request(app.getHttpServer())
      .post('/products')
      .send({ name: 'Widget', price: 9.99, categoryId: 'cat-1' })
      .expect(201);
  });

  it('POST /products — should reject invalid data', () => {
    return request(app.getHttpServer())
      .post('/products')
      .send({ name: 123, price: 'not-a-number' })
      .expect(400);
  });

  afterAll(async () => {
    await app.close();
  });
});

Anti-Patterns

Anti-PatternProblemFix
God modules (everything in one module)Unmaintainable, hard to testSplit into focused feature modules
No DTOs (accepting raw objects)No validation, security riskAlways use class-validator DTOs
Services without interfacesHard to mock, tight couplingDefine interfaces, inject by token
Missing validationBad data enters systemGlobal ValidationPipe + DTOs on every route
Synchronous operations in providersBlocks event loopUse async/await for all I/O
Direct repository access in controllersSkips business logic layerAlways go through service layer
Not using request-scoped injectionMemory leaks with shared stateUse REQUEST scope for per-request data
Throwing generic exceptionsNo useful error infoUse NestJS built-in exceptions (NotFoundException, etc.)

When NOT to Use

Do NOT use this skill when:

  • Writing application business logic (use domain-driven skill)
  • Designing database schemas (use database-design skill)
  • Writing SQL queries (use sql-best-practices skill)
  • Reviewing code for quality issues (use code-review skill)
  • Performing security audits (use security-auditor skill)
  • Analyzing deployment configurations (use deployment skill)
  • Designing multi-page website layouts (use design-system skill)
  • Reviewing git workflows (use git-workflow skill)

よくある質問

AIスキル「Nestjs」では何ができますか?

NestJS TypeScript framework development patterns — modular architecture with controllers/providers/exports, Guards for authentication (global via APP_GUARD), Pipes for validation, Interceptors for transforms, request lifecycle management, CLI schematics for code generation, and enterprise-grade patterns.

TypingMindでNestjsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Nestjsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにNestjsをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/Omar-Obando/qwen-orchestrator/tree/main/skills/nestjsを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Nestjsを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Nestjsは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもNestjsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Nestjs」は無料ですか?

はい。Omar-ObandoがGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇