中间件

wiki:

中间件Middleware, 是提供系统软件和应用软件之间连接的软件, 以便软件各部分之间的沟通, 特别是应用软件对于系统软件的集中的逻辑
在现代信息技术应用框架如Web服务、面向服务的体系结构中应用广泛、如数据库Apache的Tomcat, IBM的websphere, BEA公司的WebLogic…

Express中间件

中间件的本质就是一个函数, 在收到请求和返回响应的过程中做一些我们想要做的事情, 见如下描述:

执行任何代码, 修改请求和响应对象 -> 终结请求-> 响应循环 -> 调用堆栈中的下一个中间件

1
2
3
4
5
6
7
const express = require('express');
const app = express();

app.use('/user', function(req, res, next) {
next();
})
app.listen(8080)

Express中有以下5类中间件

  • 应用级中间件
  • 路由级中间件
  • 错误处理中间件
  • 内置中间件
  • 第三方中间件

Koa中间件

  • koa-router、koa-compress、koa-respond、kors、koa-convert、koa-bodyparser、koa-compose、koa-static

Koa2 基于async\await实现中间件

1
2
3
4
5
6
7
8
9
10
function logger(format) {
format = format || ':methos ":url"';
return async function logger(ctx, next) {
const str = format.replace(':method', ctx.method).replace(':url', ctx.url);
console.log(str);
await next();
};
}
app.use(logger());
app.use(logger(':method :url'));

Koa1 给予Generator

1
2
3
4
5
6
7
const koa = require('koa');
const app = koa();
app.use(function*(next) {
console.log('before middleware');
yield next;
console.log('after middleware');
})

Redux 中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// applyMiddleware
function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg;
}
if (funcs.length === 1) {
return funcs[0];
}

return funcs.reduce((a, b) => (...args) => a(b(...agrs)))
}

export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args);
let dispatch = () => {
throw new Error('XXXX');
}
const middlewareAPI = {
getState: store.getState,
dispatch: (...agrs) => dispatch(...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI));
dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const logger = ({getState, dispatch}) => next => action => {
console.log('before next ', action);
const returnValue = next(action);
console.log('after next, getState());
return returnValue;
}
let store = createStore(reducer, initState, applyMiddleware(logger));
/** 现在尝试发送一个 action**/
store.dispatch({
type: 'CHANGE_SCORE',
score: 0.8
})
/** 打印:**/
// 【logger】即将执行: { type: 'CHANGE_SCORE', score: 0.8 }
// 【logger】执行完成后 state: { score: 0.8 }
1
2
3
4
5
6
7
// redux-thunk
const thunk = ({getState, dispatch}) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
return next(action);
}