NodeJs 實戰——原生 NodeJS 輕仿 Express 框架從需求到實現(二)

這篇文章是一個系列的文章的第二篇,這一篇會對上一篇實現的簡易框架進行功能拓展,並將路由與應用分離,便於代碼的維護和功能拓展。爲了提高路由匹配的效率,也對路由模塊進行了進一步的設計。github地址歡迎拍磚。javascript

確認需求

  • 將路由與應用分離,便於代碼的維護和功能拓展
  • 優化路由模塊,提高匹配效率

Router 與 Application 分離

爲了將路由與應用分離,這裏咱們新增一個 Router.js 文件,用來封裝一個路由管理的類 Router,代碼以下。html

// 路由管理類
function Application() {
  // 用來保存路由的數組
  this.stack = [
    {
      path: '*',
      method: '*',
      handle: function(req, res) {
        res.writeHead(200, {
          'Content-Type': 'text/plain'
        });
        res.end('404');
      }
    }
  ];
}

Router.prototype.get = function(path, handle) {
  // 將請求路由壓入棧內
  this.stack.push({
    path,
    method: 'GET',
    handle
  });
};

Router.prototype.handle = function() {
  // 循環請求過來放入router數組的對象,當請求方法和路勁與對象一致時,執行回調handler方法
  for (var i = 1, len = this.stack.length; i < len; i++) {
    if (
      (req.url === this.stack[i].path || this.stack[i].path === '*') &&
      (req.method === this.stack[i].method || this.stack[i].method === '*')
    ) {
      return this.stack[i].handle && this.stack[i].handle(req, res);
    }
  }
  return this.stack[0].handle && this.stack[0].handle(req, res);
};
複製代碼

修改原有的 application.js 文件內容java

var Router = require('./router');
var http = require('http');

function Application() {}

Application.prototype = {
  router: new Router(),

  get: function(path, fn) {
    return this.stack.get(path, fn);
  },

  listen: function(port, cb) {
    var self = this;
    var server = http.createServer(function(req, res) {
      if (!res.send) {
        res.send = function(body) {
          res.writeHead(200, {
            'Content-Type': 'text/plain'
          });
          res.end(body);
        };
      }
      return self.router.handle(req, res);
    });
    return server.listen.apply(server, arguments);
  }
};

exports = module.exports = Application;
複製代碼

通過上面的修改,路由方面的操做只會與 Router 類自己有關,達到了與 Application 分離的目的,代碼結構更加清晰,便於後續功能的拓展。git

優化路由模塊,提高匹配效率

通過上面的實現,路由系統已經能夠正常運行了。可是咱們深刻分析一下,能夠發現咱們的路由匹配實現是會存在性能問題的,當路由不斷增多時,this.stack 數組會不斷的增大,匹配的效率會不斷下降,爲了解決匹配的效率問題,須要仔細分析路由的組成部分。 能夠看出,一個路由是由:路徑(path)、請求方式(method)和處理函數(handle)組成的。path 和 method 的關係並非簡單的一對一的關係,而是一對多的關係。以下圖,所示,對於同一個請求連接,按照RestFul API 規範 能夠實現以下相似的功能。github

基於此,咱們能夠將路由按照路徑來分組,分組後,匹配的效率能夠顯著提高。對此,咱們引入層(Layer)的概念。 這裏將 Router 系統中的 this.stack 數組的 每一項,表明一個 Layer。每一個 Layer 內部含有三個變量。

  • path,表示路由的請求路徑
  • handle,表明路由的處理函數(只匹配路徑,請求路徑一致時的處理函數)
  • route,表明真正的路由,包括 method 和 handle 總體結構以下圖所示
--------------------------------------
|        0         |        1        |
--------------------------------------
| Layer            | Layer           |
|  |- path         |  |- path        |
|  |- handle       |  |- handle      |
|  |- route        |  |- route       |
|       |- method  |       |- method |
|       |- handle  |       |- method |
--------------------------------------
            router 內部
複製代碼

建立Layer類,匹配path

function Layer(path, fn) {
  this.handle = fn;
  this.name = fn.name || '<anonumous>';
  this.path = path;
}

/** * Handle the request for the layer. * * @param {Request} req * @param {Response} res */
Layer.prototype.handle_request = function(req, res) {
  var fn = this.handle;
  if (fn) {
    fn(req, res);
  }
};

/** * Check if this route matches `path` * * @param {String} path * @return {Boolean} */
Layer.prototype.match = function(path) {
  if (path === this.path || path === '*') {
    return true;
  }
  return false;
};

module.exports = Layer;
複製代碼

修改 Router 類,讓路由通過 Layer 層包裝express

var Layer = require('./layer');
// 路由管理類
function Router() {
  // 用來保存路由的數組
  this.stack = [
    new Layer('*', function(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.end('404');
    })
  ];
}

Router.prototype.get = function(path, handle) {
  // 將請求路由壓入棧內
  this.stack.push(new Layer(path, handle));
};

Router.prototype.handle = function(req, res) {
  var self = this;
  for (var i = 1, len = self.stack.length; i < len; i++) {
    if (self.stack[i].match(req.url)) {
      return self.stack[i].handle_request(req, res);
    }
  }

  return self.stack[0].handle_request(req, res);
};

module.exports = Router;
複製代碼

建立Route類,匹配method

建立Route類,該類主要是在Layer層中匹配請求方式(method),執行對應的回調函數。這裏只實現了get請求方式,後續版本會對這一塊進行擴展。api

var Layer = require('./layer');

function Route (path) {
    this.path = path;
    this.stack = []; // 用於記錄相同路徑不一樣method的路由
    this.methods = {}; // 用於記錄是否存在該請求方式
}


/** * Determine if the route handles a given method. * @private */
Route.prototype._handles_method = function (method) {
    var name = method.toLowerCase();
    return Boolean(this.methods[name]);
}

// 這裏只實現了get方法
Route.prototype.get = function (fn) {
    var layer = new Layer('/', fn);
    layer.method = 'get';
    this.methods['get'] = true;
    this.stack.push(layer);

    return this;
}

Route.prototype.dispatch = function(req, res) {
    var self = this,
        method = req.method.toLowerCase();
    
    for(var i = 0, len = self.stack.length; i < len; i++) {
        if(method === self.stack[i].method) {
            return self.stack[i].handle_request(req, res);
        }
    }
}

module.exports = Route;
複製代碼

修改Router類,將route集成其中。數組

var Layer = require('./layer');
var Route = require('./route');
// 路由管理類
function Router() {
  // 用來保存路由的數組
  this.stack = [
    new Layer('*', function(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.end('404');
    })
  ];
}

Router.prototype.get = function(path, handle) {
  var route = this.route(path);
  route.get(handle);
  return this;
};

Router.prototype.route = function route(path) {
  var route = new Route(path);
  var layer = new Layer(path, function(req, res) {
    route.dispatch(req, res);
  });
  layer.route = route;
  this.stack.push(layer);
  return route;
};

Router.prototype.handle = function(req, res) {
  var self = this,
    method = req.method;
  for (var i = 1, len = self.stack.length; i < len; i++) {
    if (self.stack[i].match(req.url) && self.stack[i].route && self.stack[i].route._handles_method(method)) {
      return self.stack[i].handle_request(req, res);
    }
  }

  return self.stack[0].handle_request(req, res);
};

module.exports = Router;
複製代碼

總結

咱們這裏主要是建立了一個完整的路由系統,並在原始代碼基礎上引入了Layer和Route兩個概念。 目錄結構以下restful

express
  |
  |-- lib
  |    | 
  |    |-- express.js //負責實例化application對象
  |    |-- application.js //包裹app層
  |    |-- router
  |          |
  |          |-- index.js //Router類
  |          |-- layer.js //Layer類
  |          |-- route.js //Route類
  |
  |-- test
  |    |
  |    |-- index.js #測試用例
  |
  |-- index.js //框架入口
複製代碼

application表明一個應用程序,express負責實例化application對象。Router表明路由組件,負責應用程序的整個路由系統。組件內部由一個Layer數組構成,每一個Layer表明一組路徑相同的路由信息,具體信息存儲在Route內部,每一個Route內部也是Layer對象,可是Route內部的Layer和Router內部的Layer是存在必定的差別性。app

  • Router內部的Layer,主要包含path、route屬性
  • Route內部的Layer,主要包含method、handle屬性 當發起一個請求時,會先掃描router內部的每一層,而處理每層的時候會先對比URI,相同則掃描route的每一項,匹配成功則返回具體的信息,沒有任何匹配則返回未找到。
相關文章
相關標籤/搜索