1
1

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 3 years have passed since last update.

NestJS初心者が基礎を学ぶ Controller編

Last updated at Posted at 2021-09-06

はじめに

NestJSの各概念を少しづつ説明していきます。
一から学びたい人はまずこちらから

Controller

Controller は

  • 形式的には、@Controller() デコレータを適用したクラスのこと
  • 指定したパスでリクエストを処理してクライアントに応答を返すことが役割
  • Provider が提供するサービスを利用する
  • 特定の Module に属する

基本的なコントローラを作成するため、クラスとデコレータを使用する。デコレータはクラスを必要なメタデータに関連付け、ルーティングマップの作成――各リクエストを対応のコントローラに紐付ける動作を可能にする。

controllerの作成は

$ nest g controller <name>

には作成したい Controller の名前が入る。
このコマンドにより、src//.controller.ts とテスト用のファイルが作成される。
(Controller の作成に限らず、テスト用のファイルを作成したくない場合には、--no-spec を指定します。また、コマンドによる変更内容の確認だけしたい場合には、--dry-run を指定します)。

Controller の基本的な構造は以下 (公式ドキュメントからの引用)

.ts
import { Controller, Get, Post, Body } from "@nestjs/common";
import { CreateCatDto } from "./dto/create-cat.dto";
import { CatsService } from "./cats.service";
import { Cat } from "./interfaces/cat.interface";

@Controller("cats") // @Controller() デコレータの適用と Route の指定
export class CatsController {
  constructor(private catsService: CatsService) {} // 利用する Service が inject される

  @Post() // HTTP メソッドの指定
  async create(@Body() createCatDto: CreateCatDto) {// リクエストの Body を取得
    this.catsService.create(createCatDto); // 受け取った値を Service に渡す
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll(); // Service から得た値をレスポンスとして返す
  }
}

Controller を使用するためには、Module へと登録する

.ts
import { Module } from "@nestjs/common";
import { CatsController } from "./cats.controller";
import { CatsService } from "./cats.service";

@Module({
  controllers: [CatsController], // Controller の登録
  providers: [CatsService],
})
export class CatsModule {}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?