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

NestJSでAPIを作る

Posted at

今回からNestでバックエンド側の作成を始めて行きます。

APIを作る

APIを作るのは案外簡単です。
moduleとコントローラー(とサービス)を書くだけです。

それでは始めていきます

ディレクトリ構造

src/
├── app.module.ts
├── main.ts
├── controllers/
│   ├── app.controller.ts
│   └── match-data.controller.ts
├── services/
│   ├── app.service.ts
│   └── match-data.service.ts
└── modules/
    └── match-data.module.ts

今回はこのようなディレクトリ構造にしました。初心者なのでこういう分け方は良くなかったりするかもしれないですがとりあえずこのディレクトリ構造で行きます。後で変えるかもしれません。

それでは実際にAPIを作ってみましょう

moduleの設定

match-data.modules.ts

import { Module } from '@nestjs/common';
import { MatchDataController } from 'controller/match-data/match-data.controller';
import { MatchDataService } from 'feature/match-data/match-data.service';

@Module({
    controllers: [MatchDataController],
    providers: [MatchDataService],
})
export class MatchDataModule { }

MatchDataControllerMatchDataServiceを使うよ!という意味です。
例えば他のサービスなどを使いたい場合はproviders: [MatchDataService, HogeService],みたいに書きましょう。多分そのうち書くと思います。

それではMatchDataControllerMatchDataServiceを書いていきます。

コントローラーの設定

match-data.controller.ts
import { Controller, Get } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { MatchDataService } from 'feature/match-data/match-data.service';
import { WinRate } from 'feature/match-data/win-rate.dto';


@Controller('match-data')
export class MatchDataController {
    constructor(private readonly matchDataService: MatchDataService) { }

    @Get('/win-rate')
    @ApiOperation({ summary: '勝率データを取得します' })
    @ApiResponse({ status: 200, description: '勝率データが返却されました' })
    @ApiOkResponse({ description: '勝率のデータ', type:[WinRate]})
        
    async getWinRate(): Promise<WinRate[]> {
        // return this.matchDataService.getWinRates();
        return []
    }
}

全く話していませんでしたが今回はマッチデータの集計などのアプリケーションを作る予定です。
本プロジェクトではswaggerも使います。swaggerはAPIがちゃんとできているか確認するのに便利です。

では一つずつ何をしているか見ていきましょう

@Controller('match-data')

これは/match-dataのエンドポイントだよ~って事を表しています。

constructor(private readonly matchDataService: MatchDataService) {}

見ての通りにはなりますがMatchDataServiceのインスタンスmatchDataServiceを定義しています。matchDataServiceは次の記事で作ります。

@Get('/win-rate')

これはエンドポイントの定義です。以下のswaggerのドキュメントデコレーターと書き方は同じですが(同じデコレーターだから)これは大事というか必要なヤツです。
/win-rateのGETメソッドということを表しています。@Controller('match-data')と合わせると/match-data/win-rateのGETメソッドという意味になります。

@ApiOperation({ summary: '勝率データを取得します' })

これはswaggerドキュメントのデコレーターです。swaggerで見たときに何をするかを表示してくれます。

@ApiResponse({ status: 200, description: '勝率データが返却されました' })

これもswaggerのドキュメントです。何が返ってくるかを表すものとします。

@ApiOkResponse({ description: '勝率のデータ', type:[WinRate]})

同じくswaggerのドキュメントです。APIの正常な(200レスポンス)の返却値の型を明記します。
WinRate は定義しないと行けないのですがそれはまた次回

以上のデコレーターなどからこのAPIは/match-data/win-rateのGETメソッドで勝率データを取得するためのAPIで200で、WinRateの配列を勝率データとして返却するものだとわかります。

    async getWinRate(): Promise<WinRate[]> {
        // return this.matchDataService.getWinRates();
        return []
    }

ここは普通の関数です。機能というか実際の処理はサービス側で記述し、実行することになります。

最後にapp.module.tsに追加の記述をします。

app.module.ts

@Module({
  imports: [MatchDataModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Nestはapp.moduleを最初に見るみたいなのでそこにimportsとして先ほど作ったMatchDataModuleを足しましょう。これをしないと機能してくれません。

機能については次回の記事で書いていくので本記事ではこれで正しく[]が返却されることを確認して終わります。

swaggerと実際にページを開く2つの方法で確認していきます

APIの確認

image.png

こんな感じでresponse bodyが[]で返ってきているのが確認できます。

image.png

ブラウザでアクセスしても同様に値が返却されているのがわかると思います。

これでAPIが作成できました。次回は機能の実装を行います。

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