基本的に『YeomanでフロントエンドとREST APIサーバーを同時に開発する方法 - bathtimefish's blog』のスケルトン作成を AngularJS にしてそのままやっただけ。
あと CoffeeScript 使わずに Javascript で。
インストール easymock
$ npm install -g easymock
yeoman でスケルトン作成
$ mkdir easymock_sample $ cd easymock_sample $ yo angular [?] Would you like to include Twitter Bootstrap? Yes :
インストール http-proxy
$ npm install -D http-proxy
easymock の設定
$ mkdir -p server/api-server/api/items $ emacs server/api-server/api/config.json
{ "simulated-lag": 1000, "cors": false, "jsonp": false, "proxy": { "server": "http://api.realserver.com", "default": false }, "variables": { "server": "http://api.realserver.com" }, "routes": [ "/items/:itemid" ] }
ダミー作成
$ emacs server/api-server/api/items/_get.json
[ { "id": 1, "user": "john", "message": "hello" }, { "id": 2, "user": "bob", "message": "Hi!" }, { "id": 3, "user": "mike", "message": "good bye." } ]
apiサーバ起動
$ cd server/api-server $ easymock
[ { id: 1, user: "john", message: "hello" }, { id: 2, user: "bob", message: "Hi!" }, { id: 3, user: "mike", message: "good bye." } ]
表示
$ emacs app/views/main.html
<div class="hero-unit"> <h1>API Data</h1> <ul> </ul> <h3>Enjoy coding! - Yeoman</h3> </div>
$ emacs app/scripts/controllers/main.js
'use strict'; angular.module('easymockSampleApp') .controller('MainCtrl', function ($scope) { $.getJSON('api/items/', function(data) { var li, row, txt, ul, _i, _len, _results; ul = document.querySelector('div.hero-unit > ul'); _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { row = data[_i]; li = document.createElement('li'); txt = document.createTextNode("" + row.id + ", " + row.user + ", " + row.message); li.appendChild(txt); _results.push(ul.appendChild(li)); } return _results; }); return 'loading api data.'; });
プロキシサーバ
$ emacs server/proxyServer.js
var apiPath, httpProxy; httpProxy = require('http-proxy'); apiPath = '/api'; httpProxy.createServer(function(req, res, proxy) { if (req.url.indexOf(apiPath) === 0) { return proxy.proxyRequest(req, res, { host: 'localhost', port: 3000 }); } else { return proxy.proxyRequest(req, res, { host: 'localhost', port: 9000 }); } }).listen(8000); console.log("Starting Server at http://localhost:8000/");
起動
$ node server/proxyServer.js
確認