https://eggjs.org/zh-cn/basics/extend.html
extend扩展,默认都是导出一个对象,里面写方法

命名规范
扩展都是放在 app/extend目录里面的
扩展名都是有规范的
- application.js
- this.app 是对 application的扩展
 
 - context.js
- this.ctx 是对 context的扩展
 
 - request.js
 - response.js
 - helper.js
 

'use strict';const { Controller } = require('egg');class SkuController extends Controller {async index() {const { ctx, app } = this;// 查询数据库const option = {where: { id: 1 },limit: 1,offset: 1,};const res = await ctx.model.User.findAll(option);ctx.body = res;}}
application 全局应用
/app/extend/application.js
'use strict';const path = require('path');module.exports = {// 方法扩展package(key) {const pkg = getPackage();return key ? pkg[key] : pkg;},// 属性扩展get packageName() {const pkg = getPackage();return pkg.name;},// 属性扩展get allPackage() {return getPackage();},};function getPackage() {const filePath = path.join(process.cwd(), 'package.json');const pkg = require(filePath);return pkg;}
Controller中使用
async index() {const { ctx, app } = this;console.log('function', app.package('name'));console.log('attr', app.packageName, app.allPackage);}
context 上下文
对 response,request的扩展,还是和 context相关的,都是通过 ctx进行调用的
- ctx.request
 - ctx.response
 
/app/extend/context.js
'use strict';module.exports = {// 方法扩展,获取get 或 post的参数params(key) {const { method, body } = this.request;// get从 url获取参数if (method === 'GET') {return key ? this.query[key] : this.query;}return key ? body[key] : body;},// 属性扩展get User() {return this.ctx.session}};
Controller中使用
async index() {const { ctx, app } = this;const params = ctx.params() // 获取 get的 query参数const params = ctx.params('id')console.log('ctx.params', params)}
http://www.lulongwen.com/index.html?user=lucy&id=10
request 请求
/app/extend/request.js
'use strict';module.exports = {// ctx.request.tokenget token() {console.log(this.header);return this.get('token');},};
Controller中使用
async setToken() {const { ctx } = this;ctx.body = {status: 200,token: ctx.request.token,};}
response 响应
/app/extend/response.js
'use strict';module.exports = {// ctx.response.token = 'ok'set token(token) {console.log(this.header);return this.set('token', token);},};
Controller中使用
async setToken() {const { ctx } = this;ctx.response.token = 'ok';ctx.body = {status: 200,token: 'ok',};}

helper 工具库
/app/extend/helper.js
'use strict';module.exports = {// 字符串转 base64base64Encode(str = '') {return new Buffer(str).toString('base64');},};
Controller中使用
async setToken() {const { ctx } = this;const tokenEncode = ctx.helper.base64Encode('ok');ctx.response.token = tokenEncode;ctx.body = {status: 200,token: tokenEncode,};}

