LoginSignup
4

More than 5 years have passed since last update.

Json-serverでモックAPI

Posted at

Homebrew

Node.js環境準備

Homebrewインストールし

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Nodebrewインストール

brew install nodebrew

Node.jsインストール(最新バージョン)

nodebrew install-binary latest

バージョンを指定する場合には
nodebrew ls-remoteからインストールできるバージョンリストを確認して、
nodebrew use v10.12.0のようにバージョンを指定してインストールする

Node.js利用するバージョン指定

インストールされているリストを nodebrew listから確認して使う指定する

nodebrew use v10.12.0

terminalでnode commandを使えるようにする

$PATHにnodeを追加する

 echo 'export PATH=$PATH:/Users/{computer_name}/.nodebrew/current/bin/' >> ~/.bashrc

.bash_profileも使っている場合、node commandが効かない場合には.bash_profileに以下を追記する


if [ -f ~/.bashrc ] ; then
. ~/.bashrc
fi

Json Serverを使ってモックAPI

基本的な使い方はjson-serverのgithubページから確認できる
今回apiが多くまたapiごとにjsonの中身が大量に入っているため、エンドポイント毎にjsonファイルを分割する方法を参考で構築する

mkdir api-mock
cd api-mock

npm init
npm install -g json-server

mkdir api
mkdir scripts
vi merge_mock_json.js

api-mock > api には分割しているjsonファイルの置き場
api-mock > scripts > merge_mock_json.js は複数のjsonファイルを結合するスクリプトです

merge_mock_json.js
const fs = require('fs');
const path = require('path');

// ルートパスを設定
const root = path.resolve('../', 'api-mock/api');

console.log(root);

fs.watch(root, function(event, filename) {
  // /api/mock配下にあるjsonファイルの名前をエンドポイントとして読み込む
  console.log(filename);


  const api = fs.readdirSync(root).reduce((api, file) => {
    if (api === undefined) {
            api= {}
    };


    if (path.extname(file) == '.json') {
        const endpoint = path.basename(file, path.extname(file));
        console.log(endpoint);

        console.log(root + '/' + file);

        if (api[endpoint] === undefined) {
            api[endpoint] = {}
        };
        api[endpoint] = JSON.parse(fs.readFileSync(root + '/' + file, 'utf-8'));
        return api;

    }
  }, {});


  fs.writeFile(root + '/../mock.json', JSON.stringify(api), function(err) {
    if (err) throw err;
    console.log('mock file updated.');
  });

});

上記のscriptでapiフォルダにあるjsonファイルを監視して複数のjsonファイルを結合下mock.jsonを生成する

このままだとapiのroutesがhttp://localhost:3000/{jsonファイル名}になるため、routesもカスタムしたい。
http://localhost:3000/api/v1/{jsonファイル名}でアクセスできるようにする

api-mockの直下に以下のroutes.jsonファイルを作ります。

routes.json
{
  "/api/v1/*": "/$1"
}

また上記scriptとjson-serverを並列実行するため、npm-run-allというライブラリをインストールします。

npm install --save-dev npm-run-all

api-mock > package.jsonにnpm scriptsを記載します

package.json

{
  ...
  "scripts": {
    "serve": "npm-run-all -p create-mock boot-mock",
    "create-mock": "node ./scripts/merge_mock_json.js",
    "boot-mock": "json-server --watch ./mock.json --routes routes.json",
    ...
  },
  ...
}

モックAPI起動は以下のコマンドです。

npm run serve

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