nodeでAPIサーバーをつくろうとおもった時のメモ
nodeでシンプルなAPIサーバーはどう作るのが( ・∀・)イイ!!んだろう
ってことでとりあえず2つの方法でやってみました。 とりあえずAPIインターフェースをどう作るかが目的なので、RESTful*かどうかは置いときます。
*RESTfulなAPIって?→連載:ASP.NET Web API 入門:第2回 RESTfulなAPIの設計を学ぼう (2/2) - @IT
今回の選択肢
- compoundJS
- express-resource
WAFとライブラリなので比較する話じゃないですが(そもそもcompoundJSはexpressベースだし)、APIでググって引っかかった2つをチョイス。Tower.js とかもほぼcompoundJSと同じ方向性なので省略。
compoundJSでAPI作ってみる
まずはnpmでinstall.
$ sudo npm install compound -g
プロジェクト作成。
$ compound init api_sample && cd api_sample
package.jsonの内容をinstall.
$ sudo npm install -l
controllerを作成
$ compound g controller test index
routes.jsに/test/indexを追加。
exports.routes = function (map) { map.get("/test/index", "test#index"); map.all(':controller/:action'); map.all(':controller/:action/:id'); };
test_controllerを若干編集。
load('application'); action('index', function () { send({ status : 200, title: "test#index" }); });
サーバーを起動。
$ compound server
以下のようなjsonレスポンスが取れます。
{ status : 200, title: "test#index" }
express-resouceでAPI作ってみる
とりあえずinstall.
$ sudo npm install express-resource
expressが入ってない人はこちらも.
$ sudo npm install -g express
プロジェクト作るよ。
$ express api_test
package.jsonにexpress-resourceを追加して
$ sudo npm install
routes/user.jsを下記のように書き換え。 express-resourceは
express-resource provides resourceful routing to express
とあるようにREST APIのルーティングを提供してくれるもの。
module.exports = { index: function(req, res){ res.send("index: called as GET method"); } ,new: function(req, res){ res.send("new: called as GET method"); } ,create: function(req, res){ res.send("create: called as POST method"); } ,show: function(req, res){ res.send("show: called as GET method"); } ,edit: function(req, res){ res.send("edit: called as GET method"); } ,update: function(req, res){ res.send("update: called as PUT method"); } ,destroy: function(req, res){ res.send("destroy: called as DELETE method"); } };
app.jsを編集してroutingを変更します。
app.get('/', routes.index); //app.get('/users', user.list); app.resource('users', require('./routes/user'), { id: 'id' });
node app.jsをしてサーバーをたてたら、http://localhost:3000/usersにアクセス。「index: called as GET method」というレスポンスが帰ってきました。
jsonで返すようにするには、routes/user.jsでindexのところを
res.json({ "status": 200 });
と変更すれば、
{ status: 200 }
と帰ってきました。 その他にもjson、xmlなどのフォーマットの出し分けをスマートにかけたりするそう。
まとめ
apiをサクッと作るのであればcompoundJSでやろうかなーと思いました。
ormとしてSequelize ∴ A multi-dialect Object-Relational-Mapper for Node.JSというのがあってそれを使うとMVCそろってexpress でも書きやすくなりそうなのでそこまでやって比較かなーと思うけど、compoundJSに入ってるjugglingdbで問題なさそうなので,そのあたりはまたの機会に。
compoundJSはもろもろ入ってるexpressベースのようなのだがブラックボックスなところ多いのでソースを読んでみようと思う。
参考
- node.jsでSequelizeを使うための準備/前編 | Inhale n' Exhale http://h2plus.biz/hiromitsu/entry/631
- CompoundJS http://compoundjs.com/docs.html