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 1 year has passed since last update.

Prismでモックサーバー

Last updated at Posted at 2023-11-25

はじめに

マイクロサービスのプロダクトや技術的領域でチームが分割されている場合、他チームの開発を待ったりするケースがあると思います。
例えば、フロントエンドチームがバックエンドチームのAPIを待つケースなど。一時的に、DummyデータでComponentの実装を進め、後からAPIと繋ぎ込みをしたり。
このような場合、APIのモックサーバーを立てておくと、より効率的に開発を進めることができると思います。

今回は、tsoaとPrismを使って、モックサーバーを立てる方法をご紹介します。

環境

  • Node.js
  • TypeScript
  • tsoa
  • Prism

全体の流れ(ざっくり)

  1. コントローラーとモデルを定義
  2. 1の定義を元に、swagger.jsonを生成
  3. swagger.jsonを元に、Prismでモックサーバーを立てる

※ 1,2は、tsoaとOpenAPIでスキーマ駆動開発 をご参照ください。本記事は、主に3を扱います。

Prismでモックサーバーを立てる

今回は、Dockerを使用して、モックサーバーを立てます。
Dockerイメージは、stoplight/prism を使用します。swagger.jsonは、全体の流れの2で生成したものを使用します。

セットアップ

# docker-compose.yml
version: "3.8"
services:
  api-mock:
    image: stoplight/prism:5
    platform: linux/amd64
    volumes:
      - ./swagger.json:/usr/src/prism/packages/cli/swagger.json
    command: ["mock", "-h", "0.0.0.0", "-p", "4000", "swagger.json"]
    ports:
      - "4000:4000"

docker-compose.ymlの用意ができたら、コンテナを起動します。http://localhost:4000 で、モックサーバーが立ち上がればOKです。

api-mock-1  | [2:49:37 AM] › [CLI] …  awaiting  Starting Prism…
api-mock-1  | [2:49:44 AM] › [CLI] ℹ  info      POST       http://0.0.0.0:4000/users
api-mock-1  | [2:49:44 AM] › [CLI] ℹ  info      GET        http://0.0.0.0:4000/users
api-mock-1  | [2:49:44 AM] › [CLI] ▶  start     Prism is listening on http://0.0.0.0:4000

レスポンスが返ってくることも確認できます。

$ curl http://localhost:4000/users/1
{"id":"string","name":"string","status":"string"}

デフォルトのレスポンスは、string などの型が返ってきます。
値を変更したい場合は、tsoa の @Example を使用します。

レスポンスの値を変更する

Getメソッドのレスポンスを変更してみます。

export const ExampleUserResponse: UserResponse = {
  id: "52907745-7672-470e-a803-a2f8feb52944",
  name: "Example User",
  status: "active"
};
// controllers/users/user-controller.ts
@Example<UserResponse>(ExampleUserResponse) // 追加
@Get("{id}")
@SuccessResponse("200", "Return a user")
public async findUser(
  @Request() _: EXRequest,
  @Path() id: string
): Promise<UserResponse> {
  .
  .
  .
}

修正後、swagger.jsonを再生成します。
レスポンスが変更されたことを確認します。

$ curl http://localhost:4000/users/1
{"id":"52907745-7672-470e-a803-a2f8feb52944","name":"Example User","status":"active"}

以上です。

参考

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?