继续上一篇文章的学习,如果小伙伴们要回顾上一篇的内容,请点击这里 eggjs 实现服务端请求教程文档-2
五、访问 MySQL 数据库
以上是新建的数据库内容,小伙伴可以自行搭建下。
1、连接数据库
根据官网教程
在项目中安装对应的插件
npm i --save egg-mysql
or
yarn add egg-mysql
复制代码
开启插件:
/config/plugin.js
'use strict';
module.exports = {
mysql: {
enable: true,
package: 'egg-mysql',
},
};
复制代码
配置数据库信息
/config/config.default.js
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
... // 忽略重复代码
config.mysql = {
client: {
// host
host: 'localhost',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: '******',
// 数据库名
database: 'BMS',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
return {
...config,
...userConfig,
};
};
复制代码
那么至此我们的数据库配置就已经完成。
2、查询数据库
web 列表页中的 user
数据是在 egg
上写死的。
现在创建了 user
表,就通过查表来获取数据。
/app/controller/home.js
修改 userListController
的方法:
async userListController() {
const { ctx, app } = this;
const sql = 'select * from user'; // sql 语句
// 这句是重点,圈起来要考
const res = await app.mysql.query(sql); // 查询 sql 数据
ctx.body = {
data: res,
success: true,
};
}
复制代码
通过 web 界面,可以确信数据库的数据是被我们查询出来没错了。
完成了列表页,就顺手把 userDetail
的查询一起实现了吧。
async userDetailController() {
const { ctx, app } = this;
const { id } = ctx.request.body;
const sql = `select * from user where id=${id}`;
const res = await app.mysql.query(sql);
ctx.body = {
data: res,
success: true,
};
}
复制代码
六、Service 层
将请求数据库的代码提取出来,封装成 service
层。
这样做有几个好处:
- 保持
Controller
中的逻辑更加简洁 - 保持业务逻辑的独立性,抽象出来的
Service
可以被多个Controller
重复调用
在 Controller
层,我们专注于业务逻辑处理,Service
层就只做最基本的数据存取的功能。
这里有几个细节要注意:
- 文件必须要在
/app/service
下(约定优于配置) - 一个 Service 文件只能包含一个类, 这个类需要通过
module.exports
的方式返回
新建文件 /app/service/user.js
:
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async userList() {
const res = await this.app.mysql.query('select * from user');
return res;
}
async userDetail(id) {
const res = await this.app.mysql.query(`select * from user where id=${id}`);
return res;
}
}
module.exports = UserService;
复制代码
代码很好理解,就是把 Controller
层操作数据库的代码迁移到 Service
来。
修改下 Controller
层的代码,通过 Service
操作数据库。
/app/controller/home.js
async userListController() {
const { ctx, service } = this;
const res = await service.user.userList();
ctx.body = {
data: res,
success: true,
};
}
复制代码
同理,小伙伴可以自行操作下 userDetailController
的方法。
代码编写好后访问 web
端的页面,能正常请求到数据就说明没问题。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END