续接上篇~~~
Egg虽然提供了很多内置的方法,但如果有时候感觉不够用,也可以自己对Egg中的方法进行扩展。
Egg.js可以对内部的五种对象进行扩展:
可扩展对象
说明
this指向
使用方式
application
全局应用对象
app对象
this.app
context
请求上下文
ctx对象
this.ctx
request
请求级别的对象,提供了请求相关的属性和方法
ctx.request对象
this.ctx.request
response
请求级别的对象,提供了响应相关的属性和方法
ctx.response对象
this.ctx.response
helper
帮助函数
ctx.helper对象
this.ctx.helper
所有扩展内容必须写在/app/extend目录下
如果我们对application进行扩展,必须在该目录下创建application.js,扩展其他内容同理
所有可扩展对象都可以对属性和方法进行扩展
对属性进行扩展需要使用get/set关键字
application扩展 对扩展进行声明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 'use strict' module .exports = { currentTime ( ) { return getTime() }, get timeProp (){ return getTime() } } function getTime ( ) { let now = new Date () let year = now.getFullYear() let month = now.getMonth() + 1 let date = now.getDate() let nowTime = year + '/' + month + '/' +date return nowTime }
在控制器中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 'use strict' ;const Controller = require ('egg' ).Controller;class DemoController extends Controller { async extendApp ( ) { const { ctx, app } = this let nowTimeByMethod = app.currentTime() let nowTimeByProp = app.timeProp ctx.body = { extendMethod : nowTimeByMethod, extendProp : nowTimeByProp } } } module .exports = DemoController;
context扩展 声明扩展:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 'use strict' module .exports = { getParams (key ) { const method = this .request.method if (method === 'GET' ){ return key ? this .query[key] : this .query }else { return key ? this .request.body[key] : this .request.body } } }
在controller中可以通过ctx进行使用
1 2 3 4 5 6 7 8 9 10 async extendCtx ( ) { const { ctx } = this const params = ctx.getParams('name' ) ctx.body = { name : params } }
request扩展 对request扩展
1 2 3 4 5 6 7 8 9 10 11 12 'use strict' module .exports = { get token (){ return this .get('token' ) } }
request对象存在于ctx上下文中,所以需要使用ctx.request.的方式来调用
1 2 3 4 5 6 7 8 9 10 async extendReq ( ) { const { ctx } = this const token = ctx.request.token ctx.body = { token } }
response扩展 1 2 3 4 5 6 7 8 9 10 11 'use strict' module .exports = { set token (token ){ this .set('token' , token) } }
1 2 3 4 5 6 7 8 9 10 async extendRes ( ) { const { ctx } = this ctx.response.token = 'newToken' ctx.body = 'extendRes' }
helper扩展 扩展方法:
1 2 3 4 5 6 7 8 9 'use strict' module .exports = { base64Encode (str = '' ) { return new Buffer(str).toString('base64' ) } }
控制器中通过ctx.helper. 使用
1 2 3 4 5 6 7 8 9 async extendHelper ( ) { const { ctx } = this const { name } = ctx.query.name const text = ctx.helper.base64Encode(name) ctx.body = text }
上边简单演示了一下五种对象的扩展,当然实际开发中不会有这么简单的需求,但本章内容旨在入门,仅对语法进行了演示,后续自己仍需要进行深入学习。
我也会在空闲时间继续学习Egg,如果能有一些理解会继续更新内容。
那么Egg的基础入门系列就到这里啦。