LoginSignup
3
3

More than 5 years have passed since last update.

Node.jsでlaravel風ルーティング

Last updated at Posted at 2016-06-02

最近node.js始めたの者です。とは言ってもプログラマ歴もまだ浅いのですが。

今までPHPをばかりやっていたのですが、お仕事でnode.jsをやることになったので勉強がてら作ってみました。。。
PHPのLaravel風にルーテイングが出来るモジュールです!!あくまで「風」です!!!(足りない機能もたくさんあります。。。)

laravel-like-routing

今回はお仕事で使う事を目的としていたため、以下の環境で動かす事が前提になってます。

ちなみに、nodeのフレームワークはkoaを使用しています。
※他にも色々使用していますが、今回は割愛します。

module version
node v6.1.0
koa 1.2.0
koa-router 5.4.0

インストール

まずは、諸々のインストールから

npm install koa --save
npm install koa-router --save
npm install yamayamasan/laravel-like-routing --save
npm install yamayamasan/auto-requires --save

「yamayamasan/laravel-like-routing」は今回紹介する、laravel風ルーティングを実現しているモジュールです。npmに登録していないので、githubから落としてきてます。

ディレクトリ構成

project
 ├── app.js
 ├── before.js
 ├── ctrl
 │   └── user.js
 └── routing.js

サンプルコード

koaの起動とrouting.jsで定義したものを読み込んでkoa-routerに登録させてます。

project/app.js
'use strict';
// koa modules
const app = require('koa')();
const router = require('koa-router')();

// routing
const routing = require('./routing');

routing.forEach((r) => {
  if (r.before) {
    router[r.method](r.path, r.before, r.ctrl);
  } else {
    router[r.method](r.path, r.ctrl);
  }
});

app.use(router.routes());

app.use(router.allowedMethods());

if (!module.parent) app.listen(9000);

今回の記事のメインのルーテイングです。auto-requiresはこれまた自分が作ったものなのですが、あるディレクトリ配下のjsをrequireしてくれるものです。今回は「project/ctrl」配下のjsが対象です。

beforeは、メインの呼ばれる関数の前に実行さたい関数を指定します。
groupで指定すれば、そのgroup配下全てに適用されます。

※auto-requiresに関しても別記事で残しておこうかな。。。

project/routing.js
'use strict';

const _ar = require('auto-requires');
const routing = require('laravel-like-routing')({
  loader: _ar({
    root: __dirname,
    path: 'ctrl',
    jointype: 'object'
  })
});
const before = require('./before');

// http://domain/
routing.get('', function *() {
  this.body = 'hello, this is index page';
});

/**
* user.indexで poject/ctrl/user.jsのindexが呼ばれます。
*/
routing.group('user', {'before': before}, () => {
// http://domain/user/:id
  routing.get(':id', 'user.index');

  routing.group('edit', () => {
    // http://domain/user/edit/:id
    routing.post(':id', 'user.edit');
  });
});

module.exports = routing.getRules();  

before.jsです。

project/before.js
'use strict';                                                                   
/**
 * before action
 */

module.exports = function *(next) {
  console.log('before action');
  yield next;
}

Laravelでいう所のコントローラです。

project/ctrl/user.js
'use strict';

module.exports.index = function *() {
  console.log('user index action');
  const id = this.params.id;
  this.body = `this is user index, user id is ${id}`;
}

module.exports.edit = function *() {
  console.log('user edit action');
  this.body = 'this is user edit';
}

起動!!

node --harmony app.js

これで、サーバーが起動します。ポートは9000番にしているので、
http://localhost:9000
にアクセスすれば
hello, this is index page
と表示されると思います。

また、
http://localhost:9000/user/1
にアクセスすると、
this is user index, user id is 1
と表示されます。
logには

before action
user index action

と表示され、before.jsを経由して、user.indexが実行されてる事がわかります。

まとめ

とりあえず、今必要な機能だけ実装したので、現状上手く動かない所もあるかもですがそれは、徐々に改修していきたいと思います。

3
3
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
3
3