egg-mysql 实战

egg-mysql

安装

1
npm i egg-mysql --save

配置

/config/plugin.js

1
2
3
4
5
6
7
8
9
10
11
12
13
'use strict';

/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
mysql: {
enable: true,
package: 'egg-mysql',
},
};

/config/config.default.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* eslint valid-jsdoc: "off" */

'use strict';

/**
* @param {Egg.EggAppInfo} appInfo app info
*/


module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
///mysql 配置
config.mysql = {
client: {
host: '127.0.0.1',
port: '3306',
user: 'root',
password: '123456',
database: 'tab_users_info',
},
app: true,
agent: false,
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1590675198377_7658';

// add your middleware config here
config.middleware = [];

// add your user config here
const userConfig = {
// myAppName: 'egg',
};

return {
...config,
...userConfig,
};
};

使用

路由配置

/router.js

1
router.get('/user/list', controller.user.list);

服务

/service/user.js

1
2
3
4
5
6
7
8
9
10
11
'use strict';
const { Service } = require('egg');
class UserService extends Service {
// 这里可以进行各种增删改查的服务操作集合
async searchAll() {
const users = await this.app.mysql.query('select * from user_info', '');
return { users };
}

}
module.exports = UserService;

控制器

/controller/user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use strict';
const { Controller } = require('egg');
class UserController extends Controller {
async list() {
const { ctx } = this;
// 调用服务的相关操作api
const userList = await ctx.service.user.searchAll();
ctx.body = {
success: true,
data: userList,
};
}

}
module.exports = UserController;

体验

通过本次实战操作,我意识到egg的MVC框架架构,service对应model处理数据(数据库的增删改查),view对应视图模板页面,controller控制器负责处理业务逻辑