15
11

フロントエンド開発用にAPIスタブサーバーをDockerで立てる

Posted at

悩み

フロントエンドの開発をする中で、APIのリリースを待っていられないのでモックを立てたり擬似サーバーを立てたりすると思います。
今回は、その一例として簡易的にDockerでスタブを構築してみました。

ファイル構造

.
├── data/ # スタブデータを格納するフォルダ
├── Dockerfile
├── README.md
├── docker-compose.yaml
├── package.json
└── server.js

完成系のリポジトリ

使い方

準備: リポジトリのクローン

まずはクローンして作業環境の用意をします。

git clone https://github.com/Kurogoma939/stub-server.git

1. dataフォルダ配下にファイルパスに応じたファイルを作る

例えば、エンドポイントが/users/list/の場合、dataフォルダにはusers-list.jsonを作成してください。
練習としてdataフォルダの中にhello.jsonを作成してください。

2. 欲しいjsonファイルを格納する

次に、作成したhello.jsonを以下のようにしましょう

hello.json
{
    "data": {
        "message": "Hello World"
    }
}

3. dockerコンテナを立ち上げる

以下のコマンドでコンテナを立ち上げましょう

docker-compose up --build -d

4. 動作確認

では実際にスタブサーバーが機能しているか確認しましょう。
Google Chromeの拡張機能であるTalend API Testerを導入しましょう

立ち上げると以下のようになっていると思います

Screenshot 2023-10-21 17.22.44.png

このURLに、http://localhost:3003/helloを入力し、Sendボタンをクリックしてください。
そうすると、以下のように結果を取得することができると思います。

Screenshot 2023-10-21 17.23.33.png

ファイルの中身

今回は、expressを使いながら実現しました。
細かい設定をしたい方はここらへんをいじっていただければと思います。

server.js
const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
const dataDirectory = path.join(__dirname, 'data');

app.use(express.json());  // POST リクエストのボディを解析するために必要

// 共通の関数でファイルを読み込む
const handleRequest = (req, res) => {
    // エンドポイントのスラッシュをハイフンに置換し、.json拡張子を追加
    const fileName = req.path.replace(/\//g, '-').substring(1) + '.json';
    const filePath = path.join(dataDirectory, fileName);
    
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            return res.status(404).send('File not found');
        }
        res.setHeader('Content-Type', 'application/json');
        res.send(data);
    });
};

// REST APIのエンドポイントを定義
app.get('*', handleRequest);
app.post('*', handleRequest);
app.put('*', handleRequest);
app.delete('*', handleRequest);

const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
15
11
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
15
11