LoginSignup
4
2

More than 1 year has passed since last update.

NestJSの基本的な構成 ~Controller編~

Posted at

これはなに?

NestJSを業務で使い始めて1ヶ月くらいが経過しました。
ちょっと慣れてきたなと思っていたのですが
ルートモジュールに不要なモジュールをインポートしていたりなど、基本的な構成がまだわかっていないと思ったので、理解を深めるために記事にしてみました。

自分はまだ全くわかっていないと絶望の谷1に落とされたので理解を深めるために記事にしました。

今回はその中のControllerのまとめになります!

この記事のゴール

以下の理解が得られることをゴールとします

  • Controllerの役割が理解できること

Controllerってなに?

Controllerはルーティングを担っています。

具体的に言うと、ユーザーからリクエストをどのパスだったらどのような処理をするのかを決めている箇所です。

Controllerでは以下の責務を持っています。

  • URIの設計
  • ユーザーからのリクエストを受け取る

URIの設計

@Controller()デコレータを利用することでURIの設計をすることができます

cats.controller.ts
import { Controller, Get, Req } from '@nestjs/common'
import { Request } from 'express'

@Controller('cats')
export class CatsController {
  @Get('getCats')
  findAll(): string {
    return 'This action return all cats'
  }
}

上の例では@Controller('cats')@Get(’getCats’)でパスの指定をおこなっています。

なのでもし上記で書いたfindAllにリクエストを送りたい場合は以下のようになります

$ curl localhost:3000/cats/getCats
## response: This action return all cats

ユーザーからのリクエストを受け取る

先ほども出てきた@Requestでさまざまな情報を受け取れます。

デコレータ一覧 オブジェクト
@Request(), @Req() req
@Response(), @Res()* res
@Next() next
@Session() req.session
@Param(key?: string) req.params / req.params[key]
@Body(key?: string) req.body / req.body[key]
@Query(key?: string) req.query / req.query[key]
@Headers(name?: string) req.headers / req.headers[name]
@Ip() req.ip
@HostParam() req.hosts

↓引用元

User-Agent取得の例

試しにUser-Agentを取得してみます。

まずUser-Agentがどこにあるかというと

@FukuharaYohei さんの記事を引用するにrequest.headers['user-agent']にあるとわかります。

cats.controller.ts
import { Controller, Get, Req } from '@nestjs/common'
import { Request } from 'express'

@Controller('cats')
export class CatsController {
  @Get('getCats')
  findAll(@Req() req: Request): string {
console.log(req.headers['user-agent'])
    return 'This action return all cats'
  }
}

先ほどのコードを少し変えたものになります。

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

これでcats/getCatsにアクセスすると無事上記のようにUAが取得できるようになりました。

Cookie取得の例

Cookieも上のrequestから取得できます。

Cookieのget, set方法は別の記事に書いたのでこちらを参考にしてみてください。

まとめ

  • ControllerではURIの設計とユーザーからのリクエストに対する処理を記載できる

余談

実装は少しずつできるようになってきたのですが、相変わらずControllers?Providers?Modules?Services?はて??
となっているので基本的な部分をきちんと理解していこうと思います。

ではまた!

参考記事


  1. ダニング=クルーガー効果で言う谷の部分。解説はこちら 

4
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
4
2