#author("2021-12-14T02:32:36+00:00","","")
#topicpath
----


#contents

**StubbyというJSONのmockサーバを起動する [#ifd55332]
***パッケージのインストール [#t429401b]
JSONのmockサーバの構築メモ。
[[grunt-connect-proxy, grunt-stubbyを利用してAjax用のJSON(モックデータ)を取得する[grunt]>http://zkohi.hatenablog.com/entry/2013/12/24/002541]] ココ参考にさせてもらいました!!ありがとうございます。


 npm install grunt-stubby --save-dev

 mkdir -p grunt
 mkdir -p mocks/stubby/hoge

*** gruntから起動するよう、設定ファイルを記述 [#m47d073a]
 cat grunt/stubby.js

 'use strict';
  
 module.exports = function (grunt) {
 
   grunt.config('stubby', {
     stubsServer: {
       // note the array collection instead of an object
       options: {
         callback: function (server, options) {
           server.get(1, function (err, endpoint) {
             if (!err) {
               console.log(endpoint);
             }
           });
         },
         stubs: 3000,
         tls: 8443,
         admin: 8010,
         location: '0.0.0.0',
         persistent: true
       },
       files: [{
         src: ['mocks/stubby/**/*.yaml']
       }]
     }
   });
 
 };

gruntから起動するため Gruntfile.js に
 grunt.loadTasks('grunt');
と記述(( grunt.registerTask('serve', ... の真上あたりに。。))。

***stubbyの設定の記述 [#dfdab6a5]
 cat mocks/stubby/hoge.yaml

  -
  request:
    url: ^/ajax/hoge/$
    method: GET
  response:
    -
      status: 200
      headers:
        content-type: application/json
        file: mocks/stubby/hoge/get.json

 cat mocks/stubby/hoge/get.json

 {
    "foo":"1",
    "bar":"2"
 }

*** Gruntからstubbyを起動 [#qa82e1d1]
 grunt stubby
REST なクライアント((https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo/related))やブラウザから
 http://localhost:3000/ajax/hoge/
へアクセスするとJSONデータが取得できましたー。。


*** grunt serveで起動 [#e331add6]
grunt serveで起動するために serveのタスクに追加します。
 grunt.task.run([
   'clean:server',
   'wiredep',
   'concurrent:server',
   'autoprefixer:server',
   'connect:livereload',
   'stubby',  ←追加
   'watch'
 ]);


***差分。 [#cb4a7607]
https://github.com/masatomix/ui-router-sample/commit/1347af60619368d0eb34731e6d58cbc1ba61ce31


** Proxyをつかう [#g4d89021]
gruntが起動したWEBサーバから、Stubbyで起動したmockサーバにreverse proxyする設定を追加します。というのは、JavaScriptは基本的には別サーバのJSONにはアクセスできない((Same Origin Policyすね))つまりgruntのWEBサーバから落としてきたJavaScriptはgruntのJSONにしかアクセスできないので、Stubbyが動いてるmockサーバのJSONに直接アクセスすることはできません。従って、いったんgruntのWEBサーバにアクセスしてreverse proxyする必要があるわけです。

 gruntのWEBサーバの /hoge/fuga.json -- proxy --> stubbyの /hoge/fuga.json
つまりこういうことです。



[[grunt-connect-proxyのめも - yamashiro0110の日記>http://yamashiro0110.hatenadiary.jp/entry/2014/12/09/020140]] ココを参考にさせてもらいました。ありがとうございます!!

 npm install grunt-connect-proxy  --save-dev

*** Gruntfile.jsへ設定追加 [#f8786b35]
ココの下あたりに一行追加。
 // Time how long tasks take. Can help when optimizing build times
 require('time-grunt')(grunt);
 var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;


require('jit-grunt')(grunt, {
の下あたりに、
    configureProxies: 'grunt-connect-proxy',
を追加。




続いて connect.livereload.middleware あたりに以下を追加。あとproxiesの設定も追加。

 // The actual grunt server settings
 connect: {
   options: {
    割愛
   },
   proxies: [
     {
       // `localhost:9000/ajax`へのリクエストは`localhost:3000/ajax`へプロキシされるようになる
       context: '/ajax/',
       host: 'localhost',
       port: 3000
     }
   ],
   // ↑このproxies配列追加
   livereload: {
     options: {
       open: true,
       middleware: function (connect) {
         return [
           proxySnippet,    ←ココ追加
           connect.static('.tmp'),
           ... いろいろ書いてあったけど割愛。。。
         ];
       }
     }
   },
  ... 以下省略。

最後に grunt serve で起動するためのserveのタスクに追加。
    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'configureProxies',   ←ココ追加。
      'autoprefixer:server',
      'connect:livereload',
      'stubby',
      'watch'
    ]);
  });

grunt serve したあと、
 http://localhost:9000/ajax/hoge/
へアクセスしてさっきのJSONデータが取れれば成功です。。

お疲れ様でした。

***差分 [#n8b1bfa6]
https://github.com/masatomix/ui-router-sample/commit/d48210149ddd407ab5bbd4d52b870957db2baea9
なんか勝手に整形されていろいろ差分出ちゃってるけどごめんなさいって感じ(´Д`;)。。



**grunt-connect-proxy 設定いろいろ [#s1a1e98e]
***普通?の設定 [#va9dae9d]
 proxies: [
   {
      context: '/api/hogehoge01/',
     host: 'localhost',
     port: 3000
   },
   {
     context: '/api/hogehoge02/',
     host: 'localhost',
     port: 3000
   }
 ],
普通に、
http://localhost:9000/api/hogehoge01/ -> http://localhost:3000/api/hogehoge01/ などへ転送します。


***他のサーバへの転送 [#s111dac0]
 proxies: [
   {
     context: '/api/hogehoge01/',
     host: 'fugaServer',
     port: 8080
   }
 ],
http://localhost:9000/api/hogehoge01/ -> http://fugaServer:8080/api/hogehoge01/ など他のサーバへ、転送します。


***パスを書き替えて転送する [#v4a8d2d4]
たとえばTomcatへ転送する場合に http://localhost:8080/hogeapp/api/hogehoge01/ などのコンテキストパス(hogeapp)を追加したいケースです
 proxies: [
   {
     context: '/api/hogehoge01/',
     host: 'localhost',
     port: 8080,
     rewrite:{
       '^/api/hogehoge01/': '/hogeapp/api/hogehoge01/'
     }
   }
 ],
というrewrite属性をつけることで、コンテキストパスを追加することができます。








**stubby設定いろいろ [#ye126ec8]
***ファイルを返す [#mb05ed7d]
 -
   request:
     url: ^/ajax/sample1/1234$  ←完全一致
     method: GET
   response:
     -
       status: 200
       headers:
         content-type: application/json
       file: mocks/stubby/hoge/sample1.json
このファイルのJSONデータが返ります。

*** URL毎に違うJSONファイルを返す [#xbe6cd1f]
 -
    request:
      url: ^/ajax/sample2/(([a-z]{3})-([0-9]{3}))$
      method: GET
    response:
      -
        status: 200
        headers:
          content-type: application/json
        file: mocks/stubby/hoge/<% url[1] %>.json

たとえば、
  /ajax/sample2/abc-123
というリクエストに対して、
 mocks/stubby/hoge/abc-123.json
のJSONファイルを返す事ができます。

あとは正規表現のハナシですが、
 url: ^/ajax/sample2/..*\.json$
とかすれば、
 /ajax/sample2/[任意の文字列].json
に対して処理するなどもできますね。



***ファイルからでなくて、設定にデータもかける [#b623e6a7]
 -
   request:
     url: ^/ajax/sample3/(([a-z]{3})-([0-9]{3}))$
     method: GET
   response:
     -
       status: 200
       headers:
         content-type: text/html
       body:
         URL0 [<% url[0] %>] <br />
         URL1 [<% url[1] %>] <br />
         URL2 [<% url[2] %>] <br />
         URL3 [<% url[3] %>] <br />

たとえば、
  /ajax/sample3/abc-123
というリクエストに対して、
 URL0 [/ajax/sample3/abc-123] <br />
 URL1 [abc-123] <br />
 URL2 [abc] <br />
 URL3 [123] <br />
というhtmlを返す事ができます。ファイル指定でなくて、データ自体を設定に書くこともできますね。ファイルを返すときにつかったプレースホルダはデータ自体にも使えるわけですね。


***ファイルのなかでプレースホルダを使う [#o59f2b6e]
 -
   request:
     url: ^/ajax/sample4/(([a-z]{3})-([0-9]{3}))$
     method: GET
   response:
     -
       status: 200
       headers:
         content-type: text/html
       file: mocks/stubby/hoge/sample4.html

たとえば、
  /ajax/sample4/abc-123
というリクエストに対して、固定でファイルを指定します。htmlファイル自体に、
 URL0 [<% url[0] %>] <br />
 URL1 [<% url[1] %>] <br />
 URL2 [<% url[2] %>] <br />
 URL3 [<% url[3] %>] <br />
このようにプレースホルダを指定しても正しく置換されました。プレースホルダは設定ファイル内でもつかえるし、その先のファイル内でもつかえるようですね。


***レイテンシ(遅延)msを指定 [#ib47bcaa]
 -
   request:
     url: ^/ajax/sample4/(([a-z]{3})-([0-9]{3}))$
     method: GET
   response:
     -
       status: 200
       latency: 3000 ← 3秒
       headers:
         content-type: text/html
       file: mocks/stubby/hoge/sample4.html
など。。



***関連リンク [#yc256edf]
-[[stubby公式>https://www.npmjs.com/package/stubby]]
-[[上記のソース>https://github.com/masatomix/ui-router-sample/commit/085d03c199adcd62e15ece5e80513684466e2a14]]
-[[サルにもわかる正規表現入門>http://www.mnet.ne.jp/~nakama/]]
-[[Windowsユーザーに教えるLinuxの常識(6):使うほどに良さが分かる正規表現 (2/2) - @IT>http://www.atmarkit.co.jp/ait/articles/0112/04/news003_2.html]]

** grunt serveのWEBサーバを他のノードからも参照可能にする [#i96f2d5f]
Gruntfile.js において
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
コメント通り、 0.0.0.0 にすればOKぽい。

 
** karmaをつかう [#raa7cfb0]
 npm install phantomjs
 npm install jasmine-core
 npm install karma
 npm install grunt-karma
 
 grunt karma

-[[angularjs - Cannot find module 'karma' while using grunt - Stack Overflow>http://stackoverflow.com/questions/19203051/cannot-find-module-karma-while-using-grunt]]


**関連リンク [#w93bef16]
-[[Grunt: The JavaScript Task Runner>http://gruntjs.com/]]

-[[Web制作で面倒な作業を自動化するビルドツール、Grunt v0.4 入門|Web Design KOJIKA17>http://kojika17.com/2013/03/grunt.js-memo.html]]
-[[Gruntfile.jsの設定をファイル分割する[grunt] - いつかは起業したいエンジニアのブログ>http://zkohi.hatenablog.com/entry/2013/12/23/120522]]

mockとProxy関連。
-[[grunt-connect-proxy, grunt-stubbyを利用してAjax用のJSON(モックデータ)を取得する[grunt] - いつかは起業したいエンジニアのブログ>http://zkohi.hatenablog.com/entry/2013/12/24/002541]]
-[[grunt-connect-proxyのめも - yamashiro0110の日記>http://yamashiro0110.hatenadiary.jp/entry/2014/12/09/020140]]
-[[Single-page Application(SPA)でeasymock or stubbyを使ってJSON簡単開発 - albatrosary's blog>http://albatrosary.hateblo.jp/entry/2014/02/06/155004]]
-[[YeomanでフロントエンドとREST APIサーバーを同時に開発する方法 - bathtimefish's blog>http://bathtimefish.hatenablog.com/entry/2013/04/22/125127]]
-[[jit-grunt support #56 >https://github.com/drewzboto/grunt-connect-proxy/issues/56]]
-https://github.com/drewzboto/grunt-connect-proxy

----
この記事は
#vote(おもしろかった[1],そうでもない[0])
#vote(おもしろかった[2],そうでもない[0])

#comment

#topicpath

SIZE(10){現在のアクセス:&counter;}

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS