Skip to content

Commit

Permalink
docs: more detail for mysql dynamic create (#540)
Browse files Browse the repository at this point in the history
  • Loading branch information
atian25 authored and popomore committed Mar 10, 2017
1 parent 6e3e5ea commit c1464fb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
9 changes: 5 additions & 4 deletions docs/source/zh-cn/advanced/plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ exports.mysql = {
module.exports = app => {
return class PostController extends app.Controller {
*list () {
const posts = yield this.app.mysql. get('db1').query(sql, values);
const posts = yield this.app.mysql.get('db1').query(sql, values);
},
};
};
Expand All @@ -381,7 +381,7 @@ module.exports = app => {
// app.js
module.exports = app => {
app.beforeStart(function* () {
// 从配置中心获取 MySQL 的配置
// 从配置中心获取 MySQL 的配置 { host, post, password, ... }
const mysqlConfig = yield app.configCenter.fetch('mysql');
// 动态创建 MySQL 实例
app.database = app.mysql.createInstance(mysqlConfig);
Expand Down Expand Up @@ -524,10 +524,10 @@ $ npm test
```json
{
"name": "egg-view-nunjucks",
"version": "0.5.0",
"version": "1.0.0",
"description": "view plugin for egg",
"eggPlugin": {
"name": "view",
"name": "nunjucks",
"dep": [
"security"
]
Expand All @@ -537,6 +537,7 @@ $ npm test
"egg-plugin",
"eggPlugin",
"egg-plugin-view",
"egg-view",
"nunjucks"
],
}
Expand Down
16 changes: 16 additions & 0 deletions docs/source/zh-cn/tutorials/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,22 @@ const client2 = app.mysql.get('db2');
yield client2.query(sql, values);
```

#### 动态创建

我们可以不需要将配置提前申明在配置文件中,而是在应用运行时动态的从配置中心获取实际的参数,再来初始化一个实例。

```js
// {app_root}/app.js
module.exports = function(app) {
app.beforeStart(function* () {
// 从配置中心获取 MySQL 的配置
// { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' }
const mysqlConfig = yield app.configCenter.fetch('mysql');
app.database = app.mysql.createInstance(mysqlConfig);
});
};
```

## service 层

由于对 MySQL 数据库的访问操作属于 web 层中的数据处理层,因此我们强烈建议将这部分代码放在 service 层中维护。
Expand Down
1 change: 1 addition & 0 deletions test/lib/plugins/development.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ describe('test/lib/plugins/development.test.js', () => {
it('should reload when file changed', function* () {
fs.writeFileSync(filepath, 'module.exports = function*() { this.body = \'change\'; };');
// wait for app worker restart

yield sleep(10000);

yield request(app.callback())
Expand Down

0 comments on commit c1464fb

Please sign in to comment.