是一个node.js的后台web框架,相似的还有express,koa
优点:规范、插件机制
Egg.js约定了一套代码目录结构
(配置config、路由router、扩展extend、中间件middleware、控制器controller)
规范的目录结构,可使得不一样团队的开发者使用框架写出来的代码风格会更一致,接手成本也会更低。html
BFF层(先后端之间的中间层)、全栈、SSR(服务端渲染)node
框架约定的目录
app/router.js 用于配置URL路由规则 app/contorller/** 用于解析用户的输入,处理后返回相应的结果 app/service/** 用于编写业务逻辑层 【可选】 app/middleware/** 用于编写中间件 【可选】 app/service/** 用于框架的扩展 【可选】 ... 自定义的目录 app/view/** 用于防止模板文件 【可选】
Egg 将应用、框架和插件都称为加载单元(loadUnit);
在加载过程当中,Egg会遍历全部的加载单元,加载时有一点的优先级
· 插件 => 框架 => 应用依次加载
· 依赖方先加载
· 框架按继承顺序加载,越底层越先加载web
若有这样一个应用配置了以下依赖数据库
app | ├── plugin2 (依赖 plugin3) | └── plugin3 └── framework1 | └── plugin1 └── egg
最终的加载顺序为express
=> plugin1 => plugin3 => plugin2 => egg => framework1 => app
文件加载顺序
package.json => config => app/extend => app.js => app/service => app/middleware => app/controller => app/router.js
首先咱们须要配置路由
由于咱们在实际的开发中会使用不少路由因此这里咱们将路由改为分级的
在app下建立一个router文件夹用来存放路由文件home.js
//app/router/home.js 'use strict' module exports = app => { const { home } = app.controller //获取controller下的home.js app.get('/',home.index); app.get('/home/param',home.getParam); app.get('/home/postParam',home.postParam); } // app/router.js 'use strict' const RouteHome = require('./router/home'); module.exports = { const {router, controller} = app; RouteHome(app); } //app/controller/home.js 'use strict' const Controller = require('egg').Controller; class HomeController extends Controller { async index() { await this.ctx.render('/index',{name:'egg'}); } async getParam() { let id = await this.ctx.query.id; this.ctx.body = id; } async postParam(){ let id = await this.ctx.request.body.id; //获取post参数 this.ctx.body = id; } } module exports = HomeController;
咱们经过 Router 将用户的请求基于 method 和 URL 分发到了对应的 Controller 上, Controller 负责解析用户的输入,处理后返回相应的结果
框架推荐 Controller 层主要对用户的请求参数进行处理(校验、转换),而后调用对应的 service 方法处理业务,获得业务结果后封装并返回
//在app/controller目录下 新建一个controller 'use strict' const Controller = required('egg').Controller; class CustomerController extends Controller { async customIndex() { //ctx.body 是 ctx.response.body 的简写,不要和 ctx.request.body 混淆了 this.ctx.body = 'this is my controller'; } } module.exports = CustomController; //在router.js中配置路由(访问时请求的路径) 'use strict' module.exports = app => { //至关于拿到app文件夹下的router和controller const {router, controller} = app; router.get('/', controller.home.index); router.get('/custom',controller.customerController.customIndex); }
定义的 Controller 类,会在每个请求访问到 server 时实例化一个全新的对象,而项目中的 Controller 类继承于 egg.Controller,会有下面几个属性挂在 this 上
- this.ctx 框架封装好的处理当前请求的各类便捷属性和方法 - this.app 框架提供的全局对象和方法 - this.service 访问抽象出的业务层 至关于 this.ctx.service - this.config 运行的配置项 - this.logger 日志
业务逻辑层
'use strict'; const Service = require('egg').Service; class customService extends Service { async show(zc, hh) { //异步防阻塞 return zc + " and " + hh; } } module.exports = UserService; //controller代码 'use strict'; const Controller = require('egg').Controller; class CustomController extends Controller { async custonIndex() { let str = await this.ctx.service.customService.show('zc','hh'); //这里使用await来获取异步方法的返回值 this.ctx.body = 'this is my controller'+str; } } module.exports = CustomController;
一个更完整的栗子
// app/router.js module.exports = app => { app.router.get('/user/:id', app.controller.user.info); }; // app/controller/user.js const Controller = require('egg').Controller; class UserController extends Controller { async info() { const userId = ctx.params.id; const userInfo = await ctx.service.user.find(userId); ctx.body = userInfo; } } module.exports = UserController; // app/service/user.js const Service = require('egg').Service; class UserService extends Service { // 默认不须要提供构造函数。 // constructor(ctx) { // super(ctx); 若是须要在构造函数作一些处理,必定要有这句话,才能保证后面 `this.ctx`的使用。 // // 就能够直接经过 this.ctx 获取 ctx 了 // // 还能够直接经过 this.app 获取 app 了 // } async find(uid) { // 假如 咱们拿到用户 id 从数据库获取用户详细信息 const user = await this.ctx.db.query('select * from user where uid = ?', uid); // 假定这里还有一些复杂的计算,而后返回须要的信息。 const picture = await this.getPicture(uid); return { name: user.user_name, age: user.age, picture, }; } async getPicture(uid) { const result = await this.ctx.curl(`http://photoserver/uid=${uid}`, { dataType: 'json' }); return result.data; } } module.exports = UserService; // curl http://127.0.0.1:7001/user/1234
app/extend文件夹里面存放工具类
//app/extend/getName.js 'use strict' module.exports = { getUserName(id) { return list.find(i=>i.id===id).name; } } //app/extend/helper.js 'use strict' const getName = require('./getName'); module.exports = { showName() { return getName.getUserName('2221'); } } //controller引用helper 'use strict' const Controller = require('egg').Controller; class CustomController extends Controller { async customIndex() { ////this.ctx.helper拿到helper内置对象也就是进入helper.js这个文件 this.ctx.body = this.ctx.helper.showName(); } } module.exports = CustomController;
egg.js使用的是nunjucks页面模板
//在config/plugin.js里面添加 'use strict' exports.nunjucks = { enable: true, package: 'egg-view-nunjucks' } //config/config/default.js 添加 'use strict' ... module.exports = app => { ... config.view = { mapping: { '.html': 'nunjucks' }, root: path.join(appInfo.baseDir, 'app/view') } ... return config; } //app/routes/sign.js 'use strict'; module.exports = (router, controller) => { router.get('/sign/modifyPassword', controller.sign.modifyPassword); }; //app/controller/sign.js 'use strict'; const Controller = require('egg').Controller; class SignController extends Controller { async modifyPassword() { const { ctx } = this; //渲染view/sign/modifyPassword.html await ctx.render('sign/modifyPassword.html'); } } module.exports = SignController;