$30 off During Our Annual Pro Sale. View Details »
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
NestJSのはじめ方
Search
ak2ie
April 28, 2023
Programming
0
140
NestJSのはじめ方
ak2ie
April 28, 2023
Tweet
Share
More Decks by ak2ie
See All by ak2ie
SVG完全に理解してグラフ書いてみた
ak2ie
0
42
Go言語CLIツールで生産効率UPした話
ak2ie
0
110
Goではじめるバックエンド開発
ak2ie
0
68
Notion APIと学ぶNext.js
ak2ie
0
560
フロントエンドでDDDやってみた
ak2ie
0
78
初心者がシビックテックに参加してみた
ak2ie
0
110
Firebase についてとことん語りたい
ak2ie
0
110
D3.jsでグラフを描いてみた
ak2ie
0
110
Flutterはじめます
ak2ie
0
150
Other Decks in Programming
See All in Programming
S3 VectorsとStrands Agentsを利用したAgentic RAGシステムの構築
tosuri13
5
270
非同期処理の迷宮を抜ける: 初学者がつまづく構造的な原因
pd1xx
1
610
手が足りない!兼業データエンジニアに必要だったアーキテクチャと立ち回り
zinkosuke
0
400
React Native New Architecture 移行実践報告
taminif
1
130
堅牢なフロントエンドテスト基盤を構築するために行った取り組み
shogo4131
6
2k
分散DBって何者なんだ... Spannerから学ぶRDBとの違い
iwashi623
0
170
AIコーディングエージェント(NotebookLM)
kondai24
0
130
WebRTC、 綺麗に見るか滑らかに見るか
sublimer
1
150
エディターってAIで操作できるんだぜ
kis9a
0
660
スタートアップを支える技術戦略と組織づくり
pospome
8
15k
関数の挙動書き換える
takatofukui
4
770
【Streamlit x Snowflake】データ基盤からアプリ開発・AI活用まで、すべてをSnowflake内で実現
ayumu_yamaguchi
1
110
Featured
See All Featured
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
960
Automating Front-end Workflow
addyosmani
1371
200k
How to Think Like a Performance Engineer
csswizardry
28
2.3k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
36
6.2k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.3k
Faster Mobile Websites
deanohume
310
31k
Scaling GitHub
holman
464
140k
Stop Working from a Prison Cell
hatefulcrawdad
273
21k
Designing for Performance
lara
610
69k
Rails Girls Zürich Keynote
gr2m
95
14k
Being A Developer After 40
akosma
91
590k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
2.6k
Transcript
NestJSのはじめ方 2023/4/28
自己紹介 • 名前:ak2ie • システムエンジニア • 好きなもの:コーヒー
NestJSとは • Node.js上で動くバックエンドフレームワーク • TypeScriptでかける • CLIでファイルを生成可能 • ある程度決められたフォーマットに従って書くので、複数人で開発しやすい NestJSを知らない方向けに、どんな機能があるのかご紹介します
Controller NestJSの処理の流れ Middleware ログ Guard 認証 Pipe データ変換 Filter エラー制御
リクエストを処理したい!
Controller NestJSの処理の流れ
コントローラー(Controller) 【用途】 • リクエストをメインで処理 【定義方法】 • classにデコレーターをつけてController を定義 • メソッドにデコレーターをつけて処理を定
義 /cats をGETメソッドで呼び出す @Controller('cats') export class CatsController { @Get() findAll(): string { return 'This action returns all cats'; } } Controllerを定義 処理を定義
Controller • WebhookなどPOSTで呼び出された場 合、デフォルトではHTTPステータスコー ド201を返す • 200を返したい場合 @Post(‘webhook’) @HttpCode(200) hoge()
{ ……. } 例:LINE Messaging API
ログをとるには?
Controller NestJSの処理の流れ Middleware ログ
ミドルウェア(Middleware) 【用途(例)】 • ログ 【定義方法】 • @Injectableをつける • configureメソッドでセットアップ •
Expressのミドルウェアも使えます // 定義 @Injectable() export class LoggerMiddleware ... { } // 使い方 export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes('cats'); } }
認証するには?
Controller NestJSの処理の流れ Guard 認証
ガード(Guard) 【用途】 • 認証 【定義方法】 • @Injectableをつける • CanActivateメソッドで、true/falseを返 す
• @UseGuards()で使う @Injectable() export class AuthGuard implements CanActivate { canActivate( … ) { return true; } } @UseGuards(AuthGuard)
送られてきたデータを変換す るには?
Controller NestJSの処理の流れ Pipe データ変換
パイプ(Pipe) 【用途(例)】 • 送られてきたデータの変換 【定義方法】 • 標準のPipeもある • @Injectableをつけて、transformメソッド を実装する
• ParseIntPipe • ParseBoolPipe
エラー発生時のレスポンスを 変えたい!
Controller NestJSの処理の流れ Filter エラー制御
フィルタ(Filter) 【用途(例)】 • エラー発生時の返却値を制御 【実装方法】 • コントローラーでエラーをCatchして、 NestJSのHttpExceptionを投げる try {
await this.service.findAll() } catch (error) { throw new HttpException({ status: HttpStatus.FORBIDDEN, error: 'This is a custom message', }, HttpStatus.FORBIDDEN, { cause: error }); }
テストはかけるよね?
テスト • テストの雛形を作成可能 • Jestなど好きなツールを利用可能 • DI(依存性の注入)によりテスト実行が容 易 // 準備
const moduleRef = await Test.createTestingModule({ // テスト用モジュール }).compile(); catsController = moduleRef.get(CatsController); // テスト expect(await catsController.findAll()).toBe(result);
ところで、API定義書が ほしいんだけど?
OpenAPI(Swagger) • 実装に沿ったAPI定義書を表示できる • デコレータでサンプルデータを書くと、 モックサーバのレスポンスを定義できる http://localhost:3000/api
NestJSまとめ • Node.js上で動くバックエンドフレームワーク • TypeScriptでかける • テストのサポート、API定義書表示 • Controller:デコレーターで対応するHTTPメソッド等を定義 •
Middleware:ログ • Guard:認証 • Pipe:リクエストデータ変換 • Controller:処理 • Filter:エラーレスポンス変換