扩展方式
写法
在app目录下新建文件夹 extend,对什么进行扩展就新建什么文件——都是有规范的
方法扩展
app/extend/application.js
功能:获取 package.json 内容,不传参返回全部,传参返回key 对应的 value
利用 path 获取 package.json 文件路径,再require获取到内容
'use strict';const path = require('path');module.exports = {// 方法扩展// 获取 package.json 中的内容package(key) {const pack = getPack();return key ? pack[key] : pack;},};function getPack() {const filePath = path.join(process.cwd(), 'package.json');const pack = require(filePath);return pack;}
使用方法
async newApplication() {const { ctx, app } = this;const packageInfo = app.package();ctx.body = packageInfo;}
属性扩展
利用 js 对象中的 get ,使其直接成为实例的属性
// 属性扩展get allPackage() {return getPack();},
使用:
const allPack = app.allPackage
不同的扩展方式也是类似的
对context 扩展:
扩展一个 get、post 通用的 查询参数方法
app/extend/context.js
'use strict';module.exports = {// get、post 通用的 查询参数方法params(key) {// 这里面的 this 就是 ctxconst method = this.request.method;if (method === 'GET') {return key ? this.query[key] : this.query;}return key ? this.request.body[key] : this.request.body;},};
使用:
async newContext() {const { ctx } = this;const params = ctx.params();ctx.body = params;}
效果:
get
post:
注意都已经配置好了路由:
router.get('/newApplication', controller.home.newApplication);router.get('/newContext', controller.home.newContext);router.post('/newContext', controller.home.newContext);
对 request 进行扩展:
app/extend/request.js
获取get请求中请求头 header 中的 token 属性
'use strict';module.exports = {// 获得get 请求头header中 token 属性get token() {// 直接用get方式return this.get('token');},};
对 response 进行扩展:
app/extend/response.js
对 token 进行设置
'use strict';module.exports = {set token(token) {this.set('token', token);},};
使用:
async newResponse() {const { ctx } = this;const body = (ctx.response.token = 'zhoooOOO');ctx.body = body;}
对 helper 进行扩展:
扩展一个 转换 base64 的帮助函数
app/extend/helper.js
'use strict';module.exports = {base64Encode(str = '') {return new Buffer(str).toString('base64');},};
使用:
const { ctx } = this;const body = (ctx.response.token = 'zhoooOOO');const base64Body = ctx.helper.base64Encode(body);ctx.body = base64Body;
