前端网红框架的插件机制全梳理(axios、koa、redux、vuex)

开发 后端
本文将从koa、axios、vuex和redux的实现来教你怎么编写属于自己的插件机制。

前言前端中的库很多,开发这些库的作者会尽可能的覆盖到大家在业务中千奇百怪的需求,但是总有无法预料到的,所以优秀的库就需要提供一种机制,让开发者可以干预插件中间的一些环节,从而完成自己的一些需求。

本文将从koa、axios、vuex和redux的实现来教你怎么编写属于自己的插件机制。

  • 对于新手来说:本文能让你搞明白神秘的插件和拦截器到底是什么东西。
  • 对于老手来说:在你写的开源框架中也加入拦截器或者插件机制,让它变得更加强大吧!

axios

首先我们模拟一个简单的 axios,这里不涉及请求的逻辑,只是简单的返回一个 Promise,可以通过 config 中的 error 参数控制 Promise 的状态。

axios 的拦截器机制用流程图来表示其实就是这样的:

流程图

  1. const axios = config => { 
  2.   if (config.error) { 
  3.     return Promise.reject({ 
  4.       error: "error in axios" 
  5.     }); 
  6.   } else { 
  7.     return Promise.resolve({ 
  8.       ...config, 
  9.       result: config.result 
  10.     }); 
  11.   } 
  12. }; 

如果传入的 config 中有 error 参数,就返回一个 rejected 的 promise,反之则返回 resolved 的 promise。

先简单看一下 axios 官方提供的拦截器示例:

  1. axios.interceptors.request.use( 
  2.   function(config) { 
  3.     // 在发送请求之前做些什么 
  4.     return config; 
  5.   }, 
  6.   function(error) { 
  7.     // 对请求错误做些什么 
  8.     return Promise.reject(error); 
  9.   } 
  10. ); 
  11.  
  12. // 添加响应拦截器 
  13. axios.interceptors.response.use( 
  14.   function(response) { 
  15.     // 对响应数据做点什么 
  16.     return response; 
  17.   }, 
  18.   function(error) { 
  19.     // 对响应错误做点什么 
  20.     return Promise.reject(error); 
  21.   } 
  22. ); 

可以看出,不管是 request 还是 response 的拦截器,都会接受两个函数作为参数,一个是用来处理正常流程,一个是处理失败流程,这让人想到了什么?

没错,promise.then接受的同样也是这两个参数。

axios 内部正是利用了 promise 的这个机制,把 use 传入的两个函数作为一个intercetpor,每一个intercetpor都有resolved和rejected两个方法。

  1. // 把 
  2. axios.interceptors.response.use(func1, func2) 
  3.  
  4. // 在内部存储为 
  5.     resolved: func1, 
  6.     rejected: func2 

接下来简单实现一下,这里我们简化一下,把axios.interceptor.request.use转为axios.useRequestInterceptor来简单实现:

  1. // 先构造一个对象 存放拦截器 
  2. axios.interceptors = { 
  3.   request: [], 
  4.   response: [] 
  5. }; 
  6.  
  7. // 注册请求拦截器 
  8. axios.useRequestInterceptor = (resolved, rejected) => { 
  9.   axios.interceptors.request.push({ resolved, rejected }); 
  10. }; 
  11.  
  12. // 注册响应拦截器 
  13. axios.useResponseInterceptor = (resolved, rejected) => { 
  14.   axios.interceptors.response.push({ resolved, rejected }); 
  15. }; 
  16.  
  17. // 运行拦截器 
  18. axios.run = config => { 
  19.   const chain = [ 
  20.     { 
  21.       resolved: axios, 
  22.       rejected: undefined 
  23.     } 
  24.   ]; 
  25.  
  26.   // 把请求拦截器往数组头部推 
  27.   axios.interceptors.request.forEach(interceptor => { 
  28.     chain.unshift(interceptor); 
  29.   }); 
  30.  
  31.   // 把响应拦截器往数组尾部推 
  32.   axios.interceptors.response.forEach(interceptor => { 
  33.     chain.push(interceptor); 
  34.   }); 
  35.  
  36.   // 把config也包装成一个promise 
  37.   let promise = Promise.resolve(config); 
  38.  
  39.   // 暴力while循环解忧愁 
  40.   // 利用promise.then的能力递归执行所有的拦截器 
  41.   while (chain.length) { 
  42.     const { resolved, rejected } = chain.shift(); 
  43.     promisepromise = promise.then(resolved, rejected); 
  44.   } 
  45.  
  46.   // 最后暴露给用户的就是响应拦截器处理过后的promise 
  47.   return promise; 
  48. }; 

从axios.run这个函数看运行时的机制,首先构造一个chain作为 promise 链,并且把正常的请求也就是我们的请求参数 axios 也构造为一个拦截器的结构,接下来

  • 把 request 的 interceptor 给 unshift 到chain顶部
  • 把 response 的 interceptor 给 push 到chain尾部

以这样一段调用代码为例:

  1. // 请求拦截器1 
  2. axios.useRequestInterceptor(resolved1, rejected1); 
  3. // 请求拦截器2 
  4. axios.useRequestInterceptor(resolved2, rejected2); 
  5. // 响应拦截器1 
  6. axios.useResponseInterceptor(resolved1, rejected1); 
  7. // 响应拦截器 
  8. axios.useResponseInterceptor(resolved2, rejected2); 

这样子构造出来的 promise 链就是这样的chain结构:

  1.     请求拦截器2,// ↓config 
  2.     请求拦截器1,// ↓config 
  3.     axios请求核心方法, // ↓response 
  4.     响应拦截器1, // ↓response 
  5.     响应拦截器// ↓response 

至于为什么 requestInterceptor 的顺序是反过来的,仔细看看代码就知道 XD。

有了这个chain之后,只需要一句简短的代码:

  1. let promise = Promise.resolve(config); 
  2.  
  3. while (chain.length) { 
  4.   const { resolved, rejected } = chain.shift(); 
  5.   promisepromise = promise.then(resolved, rejected); 
  6.  
  7. return promise; 

promise 就会把这个链从上而下的执行了。

以这样的一段测试代码为例:

  1. axios.useRequestInterceptor(config => { 
  2.   return { 
  3.     ...config, 
  4.     extraParams1: "extraParams1" 
  5.   }; 
  6. }); 
  7.  
  8. axios.useRequestInterceptor(config => { 
  9.   return { 
  10.     ...config, 
  11.     extraParams2: "extraParams2" 
  12.   }; 
  13. }); 
  14.  
  15. axios.useResponseInterceptor( 
  16.   resp => { 
  17.     const { 
  18.       extraParams1, 
  19.       extraParams2, 
  20.       result: { code, message } 
  21.     } = resp; 
  22.     return `${extraParams1} ${extraParams2} ${message}`; 
  23.   }, 
  24.   error => { 
  25.     console.log("error", error); 
  26.   } 
  27. ); 

(1) 成功的调用

在成功的调用下输出 result1: extraParams1 extraParams2 message1

  1. (async function() { 
  2.   const result = await axios.run({ 
  3.     message: "message1" 
  4.   }); 
  5.   console.log("result1: ", result); 
  6. })(); 

(2) 失败的调用

  1. (async function() { 
  2.   const result = await axios.run({ 
  3.     error: true 
  4.   }); 
  5.   console.log("result3: ", result); 
  6. })(); 

在失败的调用下,则进入响应拦截器的 rejected 分支:

首先打印出拦截器定义的错误日志:

  1. error { error: 'error in axios' } 

然后由于失败的拦截器

  1. error => { 
  2.   console.log('error', error) 
  3. }, 

没有返回任何东西,打印出result3: undefined

可以看出,axios 的拦截器是非常灵活的,可以在请求阶段任意的修改 config,也可以在响应阶段对 response 做各种处理,这也是因为用户对于请求数据的需求就是非常灵活的,没有必要干涉用户的自由度。

vuex

vuex 提供了一个 api 用来在 action 被调用前后插入一些逻辑:

https://vuex.vuejs.org/zh/api/#subscribeaction

  1. store.subscribeAction({ 
  2.   before: (action, state) => { 
  3.     console.log(`before action ${action.type}`); 
  4.   }, 
  5.   after: (action, state) => { 
  6.     console.log(`after action ${action.type}`); 
  7.   } 
  8. }); 

其实这有点像 AOP(面向切面编程)的编程思想。

在调用store.dispatch({ type: 'add' })的时候,会在执行前后打印出日志

  1. before action add 
  2. add 
  3. after action add 

来简单实现一下:

  1. import { 
  2.   Actions, 
  3.   ActionSubscribers, 
  4.   ActionSubscriber, 
  5.   ActionArguments 
  6. } from "./vuex.type"; 
  7.  
  8. class Vuex { 
  9.   state = {}; 
  10.  
  11.   action = {}; 
  12.  
  13.   _actionSubscribers = []; 
  14.  
  15.   constructor({ state, action }) { 
  16.     this.state = state; 
  17.     this.action = action; 
  18.     this._actionSubscribers = []; 
  19.   } 
  20.  
  21.   dispatch(action) { 
  22.     // action前置监听器 
  23.     this._actionSubscribers.forEach(sub => sub.before(action, this.state)); 
  24.  
  25.     const { type, payload } = action; 
  26.  
  27.     // 执行action 
  28.     this.action[type](this.state, payload).then(() => { 
  29.       // action后置监听器 
  30.       this._actionSubscribers.forEach(sub => sub.after(action, this.state)); 
  31.     }); 
  32.   } 
  33.  
  34.   subscribeAction(subscriber) { 
  35.     // 把监听者推进数组 
  36.     this._actionSubscribers.push(subscriber); 
  37.   } 
  38.  
  39. const store = new Vuex({ 
  40.   state: { 
  41.     count: 0 
  42.   }, 
  43.   action: { 
  44.     async add(state, payload) { 
  45.       state.count += payload; 
  46.     } 
  47.   } 
  48. }); 
  49.  
  50. store.subscribeAction({ 
  51.   before: (action, state) => { 
  52.     console.log(`before action ${action.type}, before count is ${state.count}`); 
  53.   }, 
  54.   after: (action, state) => { 
  55.     console.log(`after action ${action.type},  after count is ${state.count}`); 
  56.   } 
  57. }); 
  58.  
  59. store.dispatch({ 
  60.   type: "add", 
  61.   payload: 2 
  62. }); 

此时控制台会打印如下内容:

  1. before action add, before count is 0 
  2. after action add, after count is 2 

轻松实现了日志功能。

当然 Vuex 在实现插件功能的时候,选择性的将 type payload 和 state 暴露给外部,而不再提供进一步的修改能力,这也是框架内部的一种权衡,当然我们可以对 state 进行直接修改,但是不可避免的会得到 Vuex 内部的警告,因为在 Vuex 中,所有 state 的修改都应该通过 mutations 来进行,但是 Vuex 没有选择把 commit 也暴露出来,这也约束了插件的能力。

redux

想要理解 redux 中的中间件机制,需要先理解一个方法:compose

  1. function compose(...funcs: Function[]) { 
  2.   return funcs.reduce((a, b) => (...args: any) => a(b(...args))); 

简单理解的话,就是compose(fn1, fn2, fn3) (...args) = > fn1(fn2(fn3(...args)))

它是一种高阶聚合函数,相当于把 fn3 先执行,然后把结果传给 fn2 再执行,再把结果交给 fn1 去执行。

有了这个前置知识,就可以很轻易的实现 redux 的中间件机制了。

虽然 redux 源码里写的很少,各种高阶函数各种柯里化,但是抽丝剥茧以后,redux 中间件的机制可以用一句话来解释:

把 dispatch 这个方法不断用高阶函数包装,最后返回一个强化过后的 dispatch

以 logMiddleware 为例,这个 middleware 接受原始的 redux dispatch,返回的是

  1. const typeLogMiddleware = dispatch => { 
  2.   // 返回的其实还是一个结构相同的dispatch,接受的参数也相同 
  3.   // 只是把原始的dispatch包在里面了而已。 
  4.   return ({ type, ...args }) => { 
  5.     console.log(`type is ${type}`); 
  6.     return dispatch({ type, ...args }); 
  7.   }; 
  8. }; 

有了这个思路,就来实现这个 mini-redux 吧:

  1. function compose(...funcs) { 
  2.   return funcs.reduce((a, b) => (...args) => a(b(...args))); 
  3.  
  4. function createStore(reducer, middlewares) { 
  5.   let currentState; 
  6.  
  7.   function dispatch(action) { 
  8.     currentState = reducer(currentState, action); 
  9.   } 
  10.  
  11.   function getState() { 
  12.     return currentState; 
  13.   } 
  14.   // 初始化一个随意的dispatch,要求外部在type匹配不到的时候返回初始状态 
  15.   // 在这个dispatch后 currentState就有值了。 
  16.   dispatch({ type: "INIT" }); 
  17.  
  18.   let enhancedDispatch = dispatch
  19.   // 如果第二个参数传入了middlewares 
  20.   if (middlewares) { 
  21.     // 用compose把middlewares包装成一个函数 
  22.     // 让dis 
  23.     enhancedDispatch = compose(...middlewares)(dispatch); 
  24.   } 
  25.  
  26.   return { 
  27.     dispatch: enhancedDispatch, 
  28.     getState 
  29.   }; 

接着写两个中间件

  1. // 使用 
  2.  
  3. const otherDummyMiddleware = dispatch => { 
  4.   // 返回一个新的dispatch 
  5.   return action => { 
  6.     console.log(`type in dummy is ${type}`); 
  7.     return dispatch(action); 
  8.   }; 
  9. }; 
  10.  
  11. // 这个dispatch其实是otherDummyMiddleware执行后返回otherDummyDispatch 
  12. const typeLogMiddleware = dispatch => { 
  13.   // 返回一个新的dispatch 
  14.   return ({ type, ...args }) => { 
  15.     console.log(`type is ${type}`); 
  16.     return dispatch({ type, ...args }); 
  17.   }; 
  18. }; 
  19.  
  20. // 中间件从右往左执行。 
  21. const counterStore = createStore(counterReducer, [ 
  22.   typeLogMiddleware, 
  23.   otherDummyMiddleware 
  24. ]); 
  25.  
  26. console.log(counterStore.getState().count); 
  27. counterStore.dispatch({ type: "add", payload: 2 }); 
  28. console.log(counterStore.getState().count); 
  29.  
  30. // 输出: 
  31. // 0 
  32. // type is add 
  33. // type in dummy is add 
  34. // 2 

koa

koa 的洋葱模型想必各位都听说过,这种灵活的中间件机制也让 koa 变得非常强大,本文也会实现一个简单的洋葱中间件机制。参考(umi-request 的中间件机制)

洋葱圈

对应这张图来看,洋葱的每一个圈就是一个中间件,它即可以掌管请求进入,也可以掌管响应返回。

它和 redux 的中间件机制有点类似,本质上都是高阶函数的嵌套,外层的中间件嵌套着内层的中间件,这种机制的好处是可以自己控制中间件的能力(外层的中间件可以影响内层的请求和响应阶段,内层的中间件只能影响外层的响应阶段)

首先我们写出Koa这个类

  1. class Koa { 
  2.   constructor() { 
  3.     this.middlewares = []; 
  4.   } 
  5.   use(middleware) { 
  6.     this.middlewares.push(middleware); 
  7.   } 
  8.   start({ req }) { 
  9.     const composed = composeMiddlewares(this.middlewares); 
  10.     const ctx = { req, res: undefined }; 
  11.     return composed(ctx); 
  12.   } 

这里的 use 就是简单的把中间件推入中间件队列中,那核心就是怎样去把这些中间件组合起来了,下面看composeMiddlewares方法:

  1. function composeMiddlewares(middlewares) { 
  2.   return function wrapMiddlewares(ctx) { 
  3.     // 记录当前运行的middleware的下标 
  4.     let index = -1; 
  5.     function dispatch(i) { 
  6.       // index向后移动 
  7.       iindex = i; 
  8.  
  9.       // 找出数组中存放的相应的中间件 
  10.       const fn = middlewares[i]; 
  11.  
  12.       // 最后一个中间件调用next 也不会报错 
  13.       if (!fn) { 
  14.         return Promise.resolve(); 
  15.       } 
  16.  
  17.       return Promise.resolve( 
  18.         fn( 
  19.           // 继续传递ctx 
  20.           ctx, 
  21.           // next方法,允许进入下一个中间件。 
  22.           () => dispatch(i + 1) 
  23.         ) 
  24.       ); 
  25.     } 
  26.     // 开始运行第一个中间件 
  27.     return dispatch(0); 
  28.   }; 

简单来说 dispatch(n)对应着第 n 个中间件的执行,而 dispatch(n)又拥有执行 dispatch(n + 1)的权力,

所以在真正运行的时候,中间件并不是在平级的运行,而是嵌套的高阶函数:

dispatch(0)包含着 dispatch(1),而 dispatch(1)又包含着 dispatch(2) 在这个模式下,我们很容易联想到try catch的机制,它可以 catch 住函数以及函数内部继续调用的函数的所有error。

那么我们的第一个中间件就可以做一个错误处理中间件:

  1. // 最外层 管控全局错误 
  2. app.use(async (ctx, next) => { 
  3.   try { 
  4.     // 这里的next包含了第二层以及第三层的运行 
  5.     await next(); 
  6.   } catch (error) { 
  7.     console.log(`[koa error]: ${error.message}`); 
  8.   } 
  9. }); 

在这个错误处理中间件中,我们把 next 包裹在 try catch 中运行,调用了 next 后会进入第二层的中间件:

  1. // 第二层 日志中间件 
  2. app.use(async (ctx, next) => { 
  3.   const { req } = ctx; 
  4.   console.log(`req is ${JSON.stringify(req)}`); 
  5.   await next(); 
  6.   // next过后已经能拿到第三层写进ctx的数据了 
  7.   console.log(`res is ${JSON.stringify(ctx.res)}`); 
  8. }); 

在第二层中间件的 next 调用后,进入第三层,业务逻辑处理中间件

  1. // 第三层 核心服务中间件 
  2. // 在真实场景中 这一层一般用来构造真正需要返回的数据 写入ctx中 
  3. app.use(async (ctx, next) => { 
  4.   const { req } = ctx; 
  5.   console.log(`calculating the res of ${req}...`); 
  6.   const res = { 
  7.     code: 200, 
  8.     result: `req ${req} success` 
  9.   }; 
  10.   // 写入ctx 
  11.   ctx.res = res; 
  12.   await next(); 
  13. }); 

在这一层把 res 写入 ctx 后,函数出栈,又会回到第二层中间件的await next()后面

  1. console.log(`req is ${JSON.stringify(req)}`); 
  2. await next(); 
  3. // <- 回到这里 
  4. console.log(`res is ${JSON.stringify(ctx.res)}`); 

这时候日志中间件就可以拿到ctx.res的值了。

想要测试错误处理中间件 就在最后加入这个中间件

  1. // 用来测试全局错误中间件 
  2. // 注释掉这一个中间件 服务才能正常响应 
  3. app.use(async (ctx, next) => { 
  4.   throw new Error("oops! error!"); 
  5. }); 

最后要调用启动函数:

  1. app.start({ req: "ssh" }); 

控制台打印出结果:

  1. req is "ssh" 
  2. calculating the res of ssh... 
  3. res is {"code":200,"result":"req ssh success"} 

总结

(1) axios 把用户注册的每个拦截器构造成一个 promise.then 所接受的参数,在运行时把所有的拦截器按照一个 promise 链的形式以此执行。

  • 在发送到服务端之前,config 已经是请求拦截器处理过后的结果
  • 服务器响应结果后,response 会经过响应拦截器,最后用户拿到的就是处理过后的结果了。

(2) vuex的实现最为简单,就是提供了两个回调函数,vuex 内部在合适的时机去调用(我个人感觉大部分的库提供这样的机制也足够了)。

(3) redux的源码里写的最复杂最绕,它的中间件机制本质上就是用高阶函数不断的把 dispatch 包装再包装,形成套娃。本文实现的已经是精简了 n 倍以后的结果了,不过复杂的实现也是为了很多权衡和考量,Dan 对于闭包和高阶函数的运用已经炉火纯青了,只是外人去看源码有点头秃...

(4) koa的洋葱模型实现的很精妙,和 redux 有相似之处,但是在源码理解和使用上个人感觉更优于 redux 的中间件。

中间件机制其实是非框架强相关的,请求库一样可以加入 koa 的洋葱中间件机制(如 umi-request),不同的框架可能适合不同的中间件机制,这还是取决于你编写的框架想要解决什么问题,想给用户什么样的自由度。

希望看了这篇文章的你,能对于前端库中的中间件机制有进一步的了解,进而为你自己的前端库加入合适的中间件能力。

本文所写的代码都整理在这个仓库里了:

https://github.com/sl1673495/tiny-middlewares

代码是使用 ts 编写的,js 版本的代码在 js 文件夹内,各位可以按自己的需求来看。

责任编辑:赵宁宁 来源: 前端从进阶到入院
相关推荐

2011-06-09 17:26:17

Qt 插件 API

2021-06-22 06:52:46

Vite 插件机制Rollup

2009-12-11 10:29:03

PHP插件机制

2010-09-08 14:39:35

2023-11-07 10:19:08

2011-01-21 15:02:14

jQuerywebJavaScript

2023-06-15 08:01:01

Vite插件机制

2019-12-19 08:56:21

MybatisSQL执行器

2021-03-04 08:19:29

插件机制代码

2021-12-19 07:21:48

Webpack 前端插件机制

2021-12-03 15:59:30

Nuxt3插件机制

2020-11-26 08:38:57

前端 js 库vue

2022-01-21 19:00:44

前端JS框架

2015-10-08 17:25:38

分段内存寻址Linux

2015-06-04 09:38:39

Java垃圾回收机

2015-10-09 10:22:47

分页内存寻址Linux

2022-03-11 13:01:27

前端模块

2023-03-15 11:54:32

无人驾驶系统

2020-12-10 06:01:20

前端Compose方法

2019-01-24 14:37:27

开发应用 框架
点赞
收藏

51CTO技术栈公众号