zoukankan      html  css  js  c++  java
  • ES6 HttpApplication Middleware

    const HttpRequest = function() {
      this.query = ''
    }
    
    function HttpResponse() {
      this.body = []
      this.status = 0;
    }
    
    HttpResponse.prototype.write = function(block) {
      this.body.push(block)
    }
    
    HttpResponse.prototype.display = function() {
      console.log(this.body, this.status)
    }
    
    const HttpApplication = function() {
      this.caches = []
    }
    
    HttpApplication.prototype.use = function(middleware) {
      this.caches.push(middleware)
    }
    
    HttpApplication.prototype._createPipeLineItem = (fn, next) => {
      return (req, rsp) => {
        fn.call(this, req, rsp, next)
      }
    }
    
    HttpApplication.prototype.applyRequest = function(req, rsp) {
      const middleware = this.caches.map(item => item).reverse()
    
      let lastHandler = (req, rsp) => {
        rsp.write('404')
        rsp.status = 404
      }
    
      for (let index = 0; index < middleware.length; index++) {
        const element = middleware[index];
        lastHandler = this._createPipeLineItem(element, lastHandler)
      }
    
      lastHandler(req, rsp)
    }
    
    const app = new HttpApplication()
    app.use((req, rsp, next) => {
      rsp.write('first middleware')
      next(req, rsp)
      rsp.write('first middleware end')
    })
    
    
    app.use((req, rsp, next) => {
      rsp.write('second middleware')
      rsp.status = 200
      // next(req, rsp)
    })
    
    const req = new HttpRequest()
    const rsp = new HttpResponse()
    
    app.applyRequest(req, rsp)
    
    rsp.display()
    
    
    
    
  • 相关阅读:
    HOWTO re
    数据类型
    字符串
    最大公约数
    this
    tip 2:找最小公倍数之Boost
    tip 1:一个简单的将int型转换成char的方法
    Item47
    成员函数模板
    item44:将与参数无关的代码抽离template
  • 原文地址:https://www.cnblogs.com/byxxw/p/9634323.html
Copyright © 2011-2022 走看看