1、从一个koa使用的例子开始

  1. const app = new Koa()
  2. app.use( async (ctx,next)=>{
  3. console.log('a')
  4. next()
  5. })
  6. app.use( async (ctx,next)=>{
  7. console.log('b')
  8. next()
  9. })
  10. app.on('error',err=>console.log(err))
  11. app.listen(3000,()=>console.log('server starting at 3000'))

从这个例子我们大致可以知道需要设计哪些 api:

  • 构造函数 Koa,需要一个成员变量保存中间件函数
  • 需要实现 Koa.prototype.use 方法收集中间件
  • 需要实现Koa.prototype.listen 方法启动服务器并顺序执行所有中间价,附带错误处理

2、简易实现

简易版实现的签名为 DIYKoa

2.1、 基本轮廓

  1. const http = require('http')
  2. const Event = require('events') // 实现错误监听
  3. // 1、实现构造函数,支持无 new 调用
  4. function DIYKoa(options){
  5. if(!(this instanceof DIYKoa)){
  6. return new DIYKoa(options)
  7. }
  8. Event.call(this)
  9. this.options = options
  10. this.middlewares = []
  11. }
  12. DIYKoa.prototype = EventEmitter.prototype
  13. DIYKoa.prototype.constructor = DIYKoa
  14. // 2、实现 use 方法收集中间件
  15. DIYKoa.prototype.use = function (fn) {
  16. if (typeof fn !== 'function') return
  17. this.middlewares.push(fn)
  18. return this
  19. }
  20. // 3、实现 listen 方法:启动服务器、处理中间件、错误处理
  21. DIYKoa.prototype.listen = function (...args) {
  22. const server = http.createServer(this.callback.bind(this)) // callback 是处理中间件依次调用的关键
  23. server.listen(...args)
  24. }
  25. module.exports = DIYKoa

2.2、实现细节

  1. DIYKoa.prototype.callback = function (req, res) {
  2. const ctx = this.createContext(req, res) // 封装一下 ctx 对象 , ctx 将会作为中间件函数的 this
  3. console.log(req.url);
  4. const handleRequest = () => {
  5. return res.end('hello world');
  6. } // 处理中间件执行结果
  7. const handleError = err => {
  8. this.emit('error', err)
  9. } // 触发 error 事件
  10. const fn = this.compose()
  11. fn(ctx).then(handleRequest).catch(handleError)
  12. }
  13. DIYKoa.prototype.compose = function () {
  14. return async ctx => {
  15. function createNext(middleware, oldNext) {
  16. return async () => {
  17. await middleware(ctx, oldNext);
  18. }
  19. }
  20. let len = this.middlewares.length;
  21. let next = async () => {
  22. return Promise.resolve();
  23. };
  24. for (let i = len - 1; i >= 0; i--) {
  25. let currentMiddleware = this.middlewares[i];
  26. next = createNext(currentMiddleware, next);
  27. }
  28. await next();
  29. };
  30. }
  31. DIYKoa.prototype.createContext =(req,res) => {
  32. // 源码中对 context 做了很丰富的属性代理封装,但这并不是必须的,这里简要处理
  33. const context = Object.create(null)
  34. context.req = req
  35. context.res = res
  36. return context
  37. }

2.3、验证

  1. // 1、正常情况
  2. const DIYKoa = require('./application.js')
  3. const app = new DIYKoa()
  4. app.use(async (ctx,next)=>{
  5. console.log('a')
  6. await next()
  7. })
  8. app.use(async (ctx,next)=>{
  9. console.log('b')
  10. await next()
  11. })
  12. app.on('error',err=>console.log(err))
  13. app.listen(3000,()=>console.log('server starting at 3000'))
  14. // 输出,注意这里有个坑,默认会请求两次,一次 / , 一次 /favicon.ico
  15. a b
  16. // 2、异常情况
  17. const DIYKoa = require('./application.js')
  18. const app = new DIYKoa()
  19. app.use(async (ctx,next)=>{
  20. console.log('a')
  21. await next()
  22. })
  23. app.use(async (ctx,next)=>{
  24. throw new Error('error')
  25. await next()
  26. })
  27. app.on('error',err=>console.log(err))
  28. app.listen(3000,()=>console.log('server starting at 3000'))
  29. // 输出
  30. a
  31. Error error

参考

https://github.com/airuikun/blog/issues/2
https://juejin.im/post/5c7decbbe51d454a7c5e8474