3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NestJS DIについて

Last updated at Posted at 2022-09-15

NestJSとは

効率的でスケーラブルな Node.js サーバー側アプリケーションを構築するためのフレームワークです。
プログレッシブ JavaScript を使用し、TypeScript を使用して構築され、OOP (オブジェクト指向プログラミング)、FP (関数型プログラミング)、および FRP (関数型リアクティブ プログラミング) の要素を組み合わせます。

内部では、Nest は Express (デフォルト) のような堅牢な HTTP サーバー フレームワークを利用し、オプションで Fastify を使用するように構成することもできます。

Nest は、これらの一般的な Node.js フレームワーク (Express/Fastify) より上のレベルの抽象化を提供しますが、それらの API を開発者に直接公開します。これにより、開発者は、基盤となるプラットフォームで利用可能な無数のサードパーティ モジュールを自由に使用できます。

基本的な考え方

モジュールと呼ばれる部品の単位で実装し、それをapp.module.tsでインポートすることでアプリケーションを構築していきます。ビジネスロジックに関しては、 service、ルーティング処理に関してはcontrollerが管理します。

ServiceをControllerにDIすることで、ControllerはServiceの内部構造を知る必要がなくなり、簡潔なルーティングを記述することができます。

srcのファイル構造

# src
# ├── app.controller.spec.ts // app.controller.tsのテストファイル
# ├── app.controller.ts // ルーティング処理を記述したファイル
# ├── app.module.ts // プロジェクトで使用したいモジュールをインポートすることで、アプリケーションを構築する
# ├── app.service.ts // app.controller.tsで使用するビジネスロジック
# └── main.ts // 最初にコードが実行されるエントリーポイント
# nestjsでは各機能をモジュールという単位で管理する

DI(Dependency Injection)とは

ソフトウェアを疎結合にするための設計パターンの一つです。
あるオブジェクトが必要とするオブジェクトを、そのオブジェクト自身ではなく、外部から与えることで、オブジェクトの内部構造を隠蔽し、再利用性を高めるデザインパターンのことです。
依存性の注入を行うことで、オブジェクトの生成と利用の責務を分離することができます。

NestJSでは、ServiceをControllerにDIすることで、ControllerはServiceの内部構造を知る必要がなくなります。

実例

app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}
  // 既にinstance化されたものをAppControllerのconstructorで受け取る
  // これで、AppControllerのgetHello()メソッドでAppServiceのgetHello()メソッドを呼び出せる
  // nestjsは、IoCコンテナを使って、instance化したものをAppControllerに渡している
  // instanceは、cacheされているので、同じものが何度もinstance化されることはない(=singleton)

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
app.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController], // AppControllerを使用することをここで書く
  providers: [AppService],      // controllersで使用するServiceをここで書く
})
export class AppModule {}
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule); // AppModuleをinstance化して、appに代入
  await app.listen(3005); // 3000はReactのデフォルトポートなので変更
}
bootstrap();

controllerはserviceの内部実装を知ることなく、getHello関数を利用することができています。

参考

https://docs.nestjs.com/
https://en.wikipedia.org/wiki/Dependency_injection

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?