Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

koa的AOP设计 #39

Open
spring-fe opened this issue Jan 7, 2019 · 0 comments
Open

koa的AOP设计 #39

spring-fe opened this issue Jan 7, 2019 · 0 comments

Comments

@spring-fe
Copy link
Owner

spring-fe commented Jan 7, 2019

koa的AOP设计

koa是一个web框架,比express轻量的多,koa给更像是一个中间件框架,koa只是一个基础的架子,需要用到的相应的功能时,可以用相应的中间件来实现,比如路由中间件、日志中间件等。
AOP即面向切面编程。就是在现有的代码程序中,在程序生命周期或者横向流程中加入/减去一个或多个功能,不影响原有功能。

koa的切面

  • 切面由中间件机制实现
  • 一个中间件一般有两个切面
  • 遵循先进后出的切面执行顺序,类似入栈出栈的顺序

中间件概念

如下Logger功能,可以拆分成一个独立函数。

const logger = (ctx, next) => {
  console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
  next();
}
app.use(logger);

上面代码中的logger函数就叫做"中间件"(middleware),因为它处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能。app.use()用来加载中间件。

中间件执行顺序

koa

  • 中间件执行就像洋葱一样,最早use的中间件,就放在最外层。处理顺序从左到右,左边接收一个request,右边输出返回response。
  • koa官方文档上把外层的中间件称为"上游",内层的中间件为"下游"。
  • 一般的中间件都会执行两次,调用next之前为第一次,调用next时把控制传递给下游的下一个中间件。当下游不再有中间件或者没有执行next函数时,就将依次恢复上游中间件的行为,让上游中间件执行next之后的代码。
    例如:
const one = (ctx, next) => {
  console.log('>> one');
  next();
  console.log('<< one');
}

const two = (ctx, next) => {
  console.log('>> two');
  next(); 
  console.log('<< two');
}

const three = (ctx, next) => {
  console.log('>> three');
  next();
  console.log('<< three');
}

app.use(one);
app.use(two);
app.use(three);

执行结果为:

>> one
>> two
>> three
<< three
<< two
<< one

一次http请求过程

http请求=>中间件处理=>http响应
中间件处理包含路由操作、权限处理、数据安全、数据操作、数据查询等。

koa
koa

[1]https://chenshenhai.github.io/koajs-design-note/note/chapter02/03.html
[2]https://hijiangtao.github.io/2017/11/10/Mastering-Koa-Middleware/
[3]https://cnodejs.org/topic/58fd8ec7523b9d0956dad945
[4]http://www.ruanyifeng.com/blog/2017/08/koa.html
[5]https://www.jianshu.com/p/02ed208d4577

@spring-fe spring-fe reopened this Jan 13, 2019
@spring-fe spring-fe changed the title koa koa的AOP设计 Jan 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant