怎么創(chuàng)建Egg.js項(xiàng)目, 我們這就不多講了, 可以參考我之前的文章
egg.js是什么
創(chuàng)建項(xiàng)目之后, 我們就開始配置怎么通過egg-mysql連接并操作mysql數(shù)據(jù)庫啦
安裝egg-mysql插件
cnpm i -S egg-mysql
開啟插件
config/plugin.js
module.exports = {
mysql: {
enable: true,
package: 'egg-mysql'
}
};
配置數(shù)據(jù)庫連接信息
可以配置單數(shù)據(jù)源也可以配置多數(shù)據(jù)源, 下面我們這里只講配置但數(shù)據(jù)源
在/config/config.default.js中增加數(shù)據(jù)庫配置
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {
// 數(shù)據(jù)庫配置
mysql: {
// 單數(shù)據(jù)庫信息配置
client: {
// host
host: 'ip地址',
// 端口號(hào)
port: '3306',
// 用戶名
user: 'root',
// 密碼
password: '123456',
// 數(shù)據(jù)庫名
database: 'test',
},
// 是否加載到 app 上叙甸,默認(rèn)開啟
app: true,
// 是否加載到 agent 上锨能,默認(rèn)關(guān)閉
agent: false,
}
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1565058424941_6691';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
編寫Service層代碼
這這里我們通過剛才配置的mysql直接和數(shù)據(jù)庫交互
app/service/user.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async getUserById(id) {
// 根據(jù)id查詢用戶信息
return await this.app.mysql.get('users', {id: id});
}
}
module.exports = UserService;
編寫Controller層代碼
在這里, 我們調(diào)用Service層的代碼間接和數(shù)據(jù)庫交互
app/controller/user.js
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
async index() {
// 根據(jù)id查詢用戶信息
let users = await this.ctx.service.user.getUserById(2);
this.ctx.body = users;
}
}
module.exports = UserController;
最好編寫我們的路由規(guī)則
app/router.js
module.exports = app => {
const { router, controller } = app;
// http://127.0.0.1:7001/user 會(huì)映射到app/controller/user.js 的index方法上
router.get('/user', controller.user.index);
};
到這里我們就寫完了, 一起測(cè)試一把吧
訪問: http://127.0.0.1:7001/user
{"id":2,"name":"測(cè)試2","age":11,"created_at":"2019-07-10T03:49:11.000Z","updated_at":"2019-07-24T03:49:14.000Z"}