乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      一個(gè)學(xué)習(xí) Koa 源碼的例子

       丹楓無(wú)跡 2021-10-21

      作者: MarkLin

      學(xué)習(xí)目標(biāo):

      1. 原生 node 封裝
      2. 中間件
      3. 路由

      Koa 原理

      一個(gè) nodejs 的入門(mén)級(jí) http 服務(wù)代碼如下,

      // index.js
      const http = require('http')
      const server = http.createServer((req, res) => {
        res.writeHead(200)
        res.end('hello nodejs')
      })
      
      server.listen(3000, () => {
        console.log('server started at port 3000')
      })
      

      koa 的目標(biāo)是更簡(jiǎn)單化、流程化、模塊化的方式實(shí)現(xiàn)回調(diào),我們希望可以參照 koa 用如下方式來(lái)實(shí)現(xiàn)代碼:

      // index.js
      const Moa = require('./moa')
      const app = new Moa()
      
      app.use((req, res) => {
        res.writeHeader(200)
        res.end('hello, Moa')
      })
      
      app.listen(3000, () => {
        console.log('server started at port 3000')
      })
      

      所以我們需要?jiǎng)?chuàng)建一個(gè) moa.js 文件,該文件主要內(nèi)容是創(chuàng)建一個(gè)類(lèi) Moa, 主要包含 use()listen() 兩個(gè)方法

      // 創(chuàng)建 moa.js
      const http = require('http')
      
      class Moa {
      
        use(callback) {
          this.callback = callback
        }
      
        listen(...args) {
          const server = http.createServer((req, res) => {
            this.callback(req, res)
          })
      
          server.listen(...args)
        }
      }
      
      module.exports = Moa
      

      Context

      koa 為了能夠簡(jiǎn)化 API,引入了上下文 context 的概念,將原始的請(qǐng)求對(duì)象 req 和響應(yīng)對(duì)象 res 封裝并掛載到了 context 上,并且設(shè)置了 gettersetter ,從而簡(jiǎn)化操作

      // index.js
      // ...
      
      // app.use((req, res) => {
      //   res.writeHeader(200)
      //   res.end('hello, Moa')
      // })
      
      app.use(ctx => {
        ctx.body = 'cool moa'
      })
      
      // ...
      

      為了達(dá)到上面代碼的效果,我們需要分裝 3 個(gè)類(lèi),分別是 context, request, response , 同時(shí)分別創(chuàng)建上述 3 個(gè) js 文件,

      // request.js
      module.exports = {
        get url() {
          return this.req.url
        }
        get method() {
          return this.req.method.toLowerCase()
        }
      }
      
      // response.js
      module.exports = {
        get body() {
          return this._body
        }
      
        set body(val) = {
          this._body = val
        }
      }
      
      // context.js
      module.exports = {
        get url() {
          return this.request.url
        }
        get body() = {
          return this.response.body
        }
        set body(val) {
          this.response.body = val
        }
        get method() {
          return this.request.method
        }
      }
      

      接著我們需要給 Moa 這個(gè)類(lèi)添加一個(gè) createContext(req, res) 的方法, 并在 listen() 方法中適當(dāng)?shù)牡胤綊燧d上:

      // moa.js
      const http = require('http')
      
      const context = require('./context')
      const request = require('./request')
      const response = require('./response')
      
      class Moa {
        // ...
        listen(...args) {
          const server = http.createServer((req, res) => {
            // 創(chuàng)建上下文
            const ctx = this.createContext(req, res)
      
            this.callback(ctx)
      
            // 響應(yīng)
            res.end(ctx.body)
          })
          server.listen(...args)
        }
      
        createContext(req, res) {
          const ctx = Object.create(context)
          ctx.request = Object.create(request)
          ctx.response = Object.create(response)
      
          ctx.req = ctx.request.req = req
          ctx.res = ctx.response.res = res
        }
      }
      
      

      中間件

      Koa 中間鍵機(jī)制:Koa 中間件機(jī)制就是函數(shù)組合的概念,將一組需要順序執(zhí)行的函數(shù)復(fù)合為一個(gè)函數(shù),外層函數(shù)的參數(shù)實(shí)際是內(nèi)層函數(shù)的返回值。洋蔥圈模型可以形象表示這種機(jī)制,是 Koa 源碼中的精髓和難點(diǎn)。

      洋蔥圈模型

      同步函數(shù)組合

      假設(shè)有 3 個(gè)同步函數(shù):

      // compose_test.js
      function fn1() {
        console.log('fn1')
        console.log('fn1 end')
      }
      
      function fn2() {
        console.log('fn2')
        console.log('fn2 end')
      }
      
      function fn3() {
        console.log('fn3')
        console.log('fn3 end')
      }
      

      我們?nèi)绻氚讶齻€(gè)函數(shù)組合成一個(gè)函數(shù)且按照順序來(lái)執(zhí)行,那通常的做法是這樣的:

      // compose_test.js
      // ...
      fn3(fn2(fn1()))
      

      執(zhí)行 node compose_test.js 輸出結(jié)果:

      fn1
      fn1 end
      fn2
      fn2 end
      fn3
      fn3 end
      

      當(dāng)然這不能叫做是函數(shù)組合,我們期望的應(yīng)該是需要一個(gè) compose() 方法來(lái)幫我們進(jìn)行函數(shù)組合,按如下形式來(lái)編寫(xiě)代碼:

      // compose_test.js
      // ...
      const middlewares = [fn1, fn2, fn3]
      const finalFn = compose(middlewares)
      finalFn()
      

      讓我們來(lái)實(shí)現(xiàn)一下 compose() 函數(shù),

      // compose_test.js
      // ...
      const compose = (middlewares) => () => {
        [first, ...others] = middlewares
        let ret = first()
        others.forEach(fn => {
          ret = fn(ret)
        })
        return ret
      }
      
      const middlewares = [fn1, fn2, fn3]
      const finalFn = compose(middlewares)
      finalFn()
      

      可以看到我們最終得到了期望的輸出結(jié)果:

      fn1
      fn1 end
      fn2
      fn2 end
      fn3
      fn3 end
      

      異步函數(shù)組合

      了解了同步的函數(shù)組合后,我們?cè)谥虚g件中的實(shí)際場(chǎng)景其實(shí)都是異步的,所以我們接著來(lái)研究下異步函數(shù)組合是如何進(jìn)行的,首先我們改造一下剛才的同步函數(shù),使他們變成異步函數(shù),

      // compose_test.js
      async function fn1(next) {
        console.log('fn1')
        next && await next()
        console.log('fn1 end')
      }
      
      async function fn2(next) {
        console.log('fn2')
        next && await next()
        console.log('fn2 end')
      }
      
      async function fn3(next) {
        console.log('fn3')
        next && await next()
        console.log('fn3 end')
      }
      //...
      

      現(xiàn)在我們期望的輸出結(jié)果是這樣的:

      fn1
      fn2
      fn3
      fn3 end
      fn2 end
      fn1 end
      

      同時(shí)我們希望編寫(xiě)代碼的方式也不要改變,

      // compose_test.js
      // ...
      const middlewares = [fn1, fn2, fn3]
      const finalFn = compose(middlewares)
      finalFn()
      

      所以我們只需要改造一下 compose() 函數(shù),使他支持異步函數(shù)就即可:

      // compose_test.js
      // ...
      
      function compose(middlewares) {
        return function () {
          return dispatch(0)
          function dispatch(i) {
            let fn = middlewares[i]
            if (!fn) {
              return Promise.resolve()
            }
            return Promise.resolve(
              fn(function next() {
                return dispatch(i + 1)
              })
            )
          }
        }
      }
      
      const middlewares = [fn1, fn2, fn3]
      const finalFn = compose(middlewares)
      finalFn()
      

      運(yùn)行結(jié)果:

      fn1
      fn2
      fn3
      fn3 end
      fn2 end
      fn1 end
      

      完美?。?!

      完善 Moa

      我們直接把剛才的異步合成代碼移植到 moa.js 中, 由于 koa 中還需要用到 ctx 字段,所以我們還要對(duì) compose() 方法進(jìn)行一些改造才能使用:

      // moa.js
      // ...
      class Moa {
        // ...
        compose(middlewares) {
          return function (ctx) {
            return dispatch(0)
            function dispatch(i) {
              let fn = middlewares[i]
              if (!fn) {
                return Promise.resolve()
              }
              return Promise.resolve(
                fn(ctx, function () {
                  return dispatch(i + 1)
                })
              )
            }
          }
        }
      }
      

      實(shí)現(xiàn)完 compose() 方法之后我們繼續(xù)完善我們的代碼,首先我們需要給類(lèi)在構(gòu)造的時(shí)候,添加一個(gè) middlewares,用來(lái)記錄所有需要進(jìn)行組合的函數(shù),接著在use() 方法中把我們每一次調(diào)用的回調(diào)都記錄一下,保存到middlewares 中,最后再在合適的地方調(diào)用即可:

      // moa.js
      // ...
      class Moa {
        constructor() {
          this.middlewares = []
        }
      
        use(middleware) {
          this.middlewares.push(middleware)
        }
      
        listen(...args) {
          const server = http.createServer(async (req, res) => {
            // 創(chuàng)建上下文
            const ctx = this.createContext(req, res)
            const fn = this.compose(this.middlewares)
            await fn(ctx)
            // 響應(yīng)
            res.end(ctx.body)
          })
      
          server.listen(...args)
        }
        // ...
      }
      

      我們加一小段代碼測(cè)試一下:

      // index.js
      //...
      const delay = () => new Promise(resolve => setTimeout(() => resolve()
        , 2000))
      app.use(async (ctx, next) => {
        ctx.body = "1"
        await next()
        ctx.body += "5"
      })
      app.use(async (ctx, next) => {
        ctx.body += "2"
        await delay()
        await next()
        ctx.body += "4"
      })
      app.use(async (ctx, next) => {
        ctx.body += "3"
      })
      
      

      運(yùn)行命令 node index.js 啟動(dòng)服務(wù)器后,我們?cè)L問(wèn)頁(yè)面 localhost:3000 查看一下,發(fā)現(xiàn)頁(yè)面顯示 12345 !

      到此,我們簡(jiǎn)版的 Koa 就已經(jīng)完成實(shí)現(xiàn)了。讓我們慶祝一下先!?。?/p>

      Router

      Koa 還有一個(gè)很重要的路由功能,感覺(jué)缺少路由就缺少了他的完整性,所以我們簡(jiǎn)單介紹下如何實(shí)現(xiàn)路由功能。

      其實(shí),路由的原理就是根據(jù)地址和方法,調(diào)用相對(duì)應(yīng)的函數(shù)即可,其核心就是要利用一張表,記錄下注冊(cè)的路由和方法,原理圖如下所示:

      路由原理

      使用方式如下:

      // index.js
      // ...
      const Router = require('./router')
      const router = new Router()
      
      router.get('/', async ctx => { ctx.body = 'index page' })
      router.get('/home', async ctx => { ctx.body = 'home page' })
      router.post('/', async ctx => { ctx.body = 'post index' })
      app.use(router.routes())
      
      // ...
      

      我們來(lái)實(shí)現(xiàn)下 router 這個(gè)類(lèi),先在根目錄創(chuàng)建一個(gè) router.js 文件,然后根據(jù)路由的原理,我們實(shí)現(xiàn)下代碼:

      // router.js
      class Router {
        constructor() {
          this.stacks = []
        }
      
        register(path, method, middleware) {
          this.stacks.push({
            path, method, middleware
          })
        }
      
        get(path, middleware) {
          this.register(path, 'get', middleware)
        }
      
        post(path, middleware) {
          this.register(path, 'post', middleware)
        }
      
        routes() {
          return async (ctx, next) => {
            let url = ctx.url === '/index' ? '/' : ctx.url
            let method = ctx.method
            let route
            for (let i = 0; i < this.stacks.length; i++) {
              let item = this.stacks[i]
              if (item.path === url && item.method === method) {
                route = item.middleware
                break
              }
            }
      
            if (typeof route === 'function') {
              await route(ctx, next)
              return
            }
      
            await next()
          }
        }
      }
      
      module.exports = Router
      

      啟動(dòng)服務(wù)器后,測(cè)試下 loacalhost:3000, 返回頁(yè)面上 index page 表示路由實(shí)現(xiàn)成功!

      本文源碼地址: https://github.com/marklin2012/moa/


      歡迎關(guān)注凹凸實(shí)驗(yàn)室博客:

      或者關(guān)注凹凸實(shí)驗(yàn)室公眾號(hào)(AOTULabs),不定時(shí)推送文章:

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶(hù) 評(píng)論公約

        類(lèi)似文章 更多