LoginSignup
0
0

More than 3 years have passed since last update.

node-easymockでクエリパラメータに応じたjsonを返す方法

Posted at

目的

easymockってどれくらいのアクティブユーザー数がいるかわかりませんが、自分の担当した案件では使っていたのでそのときのtipsをメモ。

やりたいことは以下のようなリクエストがあったとして、クエリパラメータに応じた場合分けで異なる形式のjsonを返すこと。
easymockでは、URLパスごとに静的なjsonファイルを準備するため、クエリパラメータでの出し分けがちょっと工夫が必要です。
クエリパラメータを見て条件分岐して、利用する静的jsonファイルを選択するイメージですが、easymockではifのような条件分岐は使えないのでそれを代替する手段を記載します。

リクエスト
GET /search?type=sales&year=2015
GET /search?type=engineer&year=2020
レスポンス
# type=sales&year=2015の場合
[
  {
    "id": 150101
  }
]

# type=engineer&year=2020の場合
[
  {
    "id": 200201
  }
]

結論

利用するバージョン:0.2.28

ディレクトリ構造
mock/
├ config.json
└ search_get.json
config.json
{
  "variables": {
    "sales_2015": 150101,
    "engineer_2020": 200201
  }
}
search_get.json
[
  {
    "id": #{#{type}_#{year}}
  }
]

解説

easymockには予め設定できる変数と、クエリパラメータを格納する変数があります。

今回はこれを組み合わせて同じjsonファイルだけを利用して、2つのクエリパラメータの組み合わせでレスポンスデータを変えています。

変数展開には#{...}が利用でき、かつこれを入れ子にできる点がポイント。

ドキュメントには、今回のケースにバッチリはまる使い方が載っていませんでしたが、テストコードを読むとそれっぽいことができることに気が付きました。

node-easymock/test/mock.test.coffee
    it '#{name_#lang} should be replaced correctly with #lang = de -> #{name_de} => Patrick', (done) ->
      request 'get', '/with_variable_within_variable?lang=de', (res) ->
        res.statusCode.should.equal 200
        json = JSON.parse res.body
        json.should.have.property('name').and.equal 'Patrick'
        done()

https://github.com/CyberAgent/node-easymock/blob/master/test/mock.test.coffee#L152-L157

node-easymock/test/mock_data/with_variable_within_variable_get.json
{
  "name": "#{name_#{lang}}"
}

https://github.com/CyberAgent/node-easymock/blob/master/test/mock_data/with_variable_within_variable_get.json

node-easymock/test/mock_data/config.json
{
  "variables" : {
    "server": "http://server.com",
    "name_de": "Patrick"
  },
  "routes": [
    "/groups/:groupid",
    "/groups/:groupid/show",
    "/groups/:groupid/users/:userid"
  ],
  "proxy": {
    "server": "http://real.com",
    "default": false,
    "calls": {
      "/proxy": true
    }
  }
}

https://github.com/CyberAgent/node-easymock/blob/master/test/mock_data/config.json

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