续接上篇~~~
中间件
egg中间件与koa一致保持洋葱模型
按照约定中间件必须位于/app/middleware目录下
全局使用中间件
定义一个全局中间件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 'use strict'
module.exports = options => { return async (ctx, next) => { if(ctx.session.counter){ ctx.session.counter ++ } else { ctx.session.counter = 1 } await next() } }
|
中间件想要在区局使用必须在config中进行一些配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 'use strict';
module.exports = appInfo => { const config = exports = {};
config.middleware = ['counter'];
return { ...config }; };
|
指定路由使用中间件
可以将中间件应用于指定路由:
- 在config中取消对于中间件的全局配置
- 在router中取出中间件并将其配置到指定路由中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
'use strict';
module.exports = appInfo => { const config = exports = {};
config.middleware = [];
return { ...config }; };
|
1 2 3 4 5 6 7 8 9 10 11 12
| 'use strict';
module.exports = app => { const counter = app.middleware.counter() const { router, controller } = app; router.get('/mid4path', counter, controller.demo.useMiddleWare) };
|
中间件的执行顺序
前边说过Egg中的中间件是严格遵守洋葱模型的,可以看如下示例:
假设有如下路由:
1 2 3 4 5 6 7 8
| 'use strict';
module.exports = app => { const { router, controller } = app; router.get('/testMiddleWare', controller.home.testMiddleWare) };
|
控制器代码如下:
1 2 3 4 5 6
| async testMiddleWare(){ const ctx = this.ctx console.log('控制器') ctx.body = 'success' }
|
编写两个中间件并在config中进行配置:
1 2 3 4 5 6 7 8 9 10
| 'use strict'
module.exports = options => { return async (ctx, next) => { console.log('一号中间件1') await next() console.log('一号中间件2') } }
|
1 2 3 4 5 6 7 8 9 10
| 'use strict'
module.exports = options => { return async (ctx, next) => { console.log('二号中间件1') await next() console.log('二号中间件2') } }
|
1 2
| config.middleware = ['demo', 'test'];
|
从代码可以看出我们定义了两个中间件,在next前后分别进行了输出来演示洋葱模型的效果。
在config中我们定义中间件的顺序为demo在前。test在后。
所以我们访问路由应该会依次访问 demo -> test -> controller -> test -> demo
事实上控制台确实会依次打印如下内容:
1 2 3 4 5
| 一号中间件1 二号中间件1 控制器 二号中间件2 一号中间件2
|
定时任务
定时任务必须放到/app/schedule目录下
定时任务的方式与Controller类似,但是类中的方法命名也有具体要求
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
| 'use strict'
const Subscription = require('egg').Subscription
class GetTime extends Subscription { static get schedule(){ return { interval: '10s', type: 'worker' } } async subscribe(){ console.log('run schedule') } }
module.exports = GetTime
|
我们如上定义好一个定时任务之后,不需要做额外的配置,只要启动程序,定时任务就会启动。