egg 入门到上线
一、入门
- 采用脚手架进行项目框架搭建
npm init egg --type=simple
- 启动项目进行测试
npm run dev
- 不出意外,项目运行在
http://127.0.0.1:7001
二、进阶
2.1 controller
层
这里采用了前后分离的开发模式,统一返回了json格式
// app/controller/home.js
// 严格模式
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const {
ctx } = this;
// 在这里去写你的业务逻辑
ctx.body = {
code:200,
message:'测试demo'
}
}
}
// app/router.js
// 将控制器,绑定给路由
// 区分前端路由,和后端路由的区别
// 前端路由对应视图文件
// 后端路由对应业务逻辑
'use strict';
module.export = app => {
const {
router,controller} = app
router.get('/',controller.home.index)
}
- 对应返回的json
{
"code":200,
"message":"测试demo"
}
2.2 作为一个mvc
框架怎么能没有service
?
service
层定义
// app/service/home.js
'use strict';
const Service = require('egg').Service
class HomeService extends Service{
async index(){
// service 一般去操作数据库
}
}
module.export = HomeService
2.3 有了service,怎么能没有数据库?
这里采用了egg-sequelize
和 mysql2
npm install --save egg-sequelize mysql2
装好之后开始配置
// config/plugin.js
'use strict';
module.exports = {
/* 数据库 */
sequelize:{
enable:true,
package:'egg-sequelize'
}
}
// config.default.js
'use strict';
module.exports = appInfo => {
const config = exports = {
};
// ...
config.sequelize = {
dialect: 'mysql',// 采用mysql
host:'127.0.0.1',// 数据库主机,**string 类型!!!**
port:3306, // 数据库端口 **number类型 !!!**
database:'dbName', // 数据库名称,确保数据库中有,不然报错
username:'root',
password:'123456',
timezone:'+08:00',// 时区问题 +8:00
dialectOptions: {
// 让读取date类型数据时返回字符串而不是UTC时间
dateStrings: true,
typeCast(field, next) {
if (field.type === 'DATETIME') {
return field.string();
}
return next();
},
},
}
}
注意事项:
host:'127.0.0.1'
// 数据库主机,string 类型!!!port:3306
// 数据库端口 number类型 !!!database:'dbName'
// 数据库名称,确保数据库中有,不然报错timezone:'+08:00'
// 时区问题 +8:00- UTC时间转字符串
不报错进行下一步
2.4 有了egg-sequelize
,怎么能没有model
?
建立第一个model
// app/model/user.js
'use strict';
module.exports = app => {
const {
STRING,INTEGER,DATE} = app.Sequelize;
const User = app.model.define('b_user',{
id:{
type:STRING,
primaryKey:true,// 主键
autoIncrement:true // 自增
},
birthday:{
type:DATE,
defaultValue:null
},
phone: {
type: STRING,
unique: true,// 唯一
defaultValue: null,
},
})
app.beforeStart(async function() {
// 应用会等待这个函数执行完成才启动
// 开发模式下,修改了模型结构去同步数据库(表不存在的情况下)
await app.model.sync();
});
// 表关联 associate
User.associate = () => {
app.model.User.belongsTo(app.model.Article, {
foreignKey: 'user_id', targetKey: 'id' });
};
return User
}
注意事项:
-
建立模型时,文件名称需要注意,
- 文件名称
user.js
,调用时app.model.User
,此时**U
大写**
- 文件名称
-
类型在
app.Sequelize
中导出 -
定义自增组件时
type:INTEGER
,数字类型,不然报错 -
定义默认值和sequelize有所不同
default
,egg-sequelize
特例独行defaultValue
-
在进行表关联的时候,建立模型时就需要采用
associate
进行关联其他模型belongsTo()
属于一个belongsMany()
属于多个hasOne()
拥有一个hasMany()
拥有多个- 等会看下面
2.4.1 插入数据
- 单条数据插入
app.model.xxx.crete()
- 多条数据插入
app.model.xxx.blukCreate()
// app/service/user.js
'use strict'