2
2

More than 1 year has passed since last update.

【NestJS】基本アーキテクチャまとめ(Module,Controller,Service)

Posted at

大きく分けて3つある

Module

@Moduleデコレータのプロパティ
・providers: @Injectableデコレータが付いたクラスを記述
・controllers @Controllerデコレータが付いたクラスを記述
・imports: モジュール内部で必要な外部モジュールを記述
・exports: 外部のモジュールにエクスポートしたいもの

以下はサンプル ・ユーザー機能を作成したとする
app.module.ts
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { UsersModule } from "./users/users.module";

@Module({
  imports: [UsersModule], // 作成したUsersModuleをimportsで読み込んで適用する
  controllers: [AppController],
  providers: [AppService],
  exports: []
})
users.module.ts
import { Module } from "@nestjs/common";
import { UsersController } from "./users/users.controller";
import { UsersService } from "./users/users.service";

@Module({
  imports: [],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService], // 外部で利用したい場合exportsに書く、ここではapp.module.tsで使いたい
})

Controller

クライアントからのリクエストを受けて、レスポンスを返す役割

@Controllerデコレーターをつける

users.controller.ts
import { Controller, Post } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post() // HTTPメソッドデコレーターをつける
  create() {
    // ユーザー作成のロジック
  }
}

Service

・ロジックを定義する(ビジネスロジックと説明されることが多いが要はロジックの認識)
・Controllerにロジックを書いてもプログラムは動く
→なぜ分けている?

Controllerの役割とロジックの役割を分担することで保守性拡張性を上げる

DI(Dependency Injection)とは
・Controllerの役割とServiceの役割を分けて、依存性を下げること
→依存関係のあるオブジェクトを外部から注入する(ServiceをControllerに注入)

メリット
・本番用、テスト用のインスタンスの切り替え
・ログの出力先の切り替え

@Injectable()デコレーターをつける ※@Serviceではない

users.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  find(userName: string) {
  // ビジネスロジック
  }
}

ControllerからServiceを利用する方法

1 ModuleのprovidersにServiceを登録する

users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users/users.controller';
import { UsersService } from './users/users.service';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

2 ControllerのconstructorでServiceを引数に取る

users.controller.ts
import { Get, Param } from '@nestjs/common';
import { UsersService } from './users/users.service';

export class UsersController {
  constructor(private readonly userService: UsersService) {}
  @Get('username')
  find(@Param('username') userName: string) {
    this.userService.find(userName);
  }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2