Skip to content

Commit 7fc6e34

Browse files
authored
refactor: refactor sequelize example (#83)
1 parent ff9f38c commit 7fc6e34

29 files changed

+415
-1148
lines changed

.travis.yml

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ node_js:
44
- '10'
55
- '8'
66
services:
7-
- postgresql
7+
- mysql
88
before_install:
99
- 'wget https://archive.apache.org/dist/zookeeper/zookeeper-3.4.6/zookeeper-3.4.6.tar.gz'
1010
- 'tar xf zookeeper-3.4.6.tar.gz'
1111
- 'mv zookeeper-3.4.6/conf/zoo_sample.cfg zookeeper-3.4.6/conf/zoo.cfg'
1212
- './zookeeper-3.4.6/bin/zkServer.sh start'
13+
- mysql -e 'CREATE DATABASE IF NOT EXISTS `egg-sequelize-example-unittest`;'
1314
install:
1415
- npm i npminstall && npminstall
1516
script:

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
"autod": "^2.7.1",
1111
"autod-egg": "^1.0.0",
1212
"chalk": "^1.1.3",
13-
"egg-ci": "^1.6.0",
1413
"eslint": "4",
1514
"eslint-config-egg": "5",
1615
"npminstall": "3",

sequelize-example/.autod.conf.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'ues strict';
2+
3+
module.exports = {
4+
write: true,
5+
prefix: '^',
6+
devprefix: '^',
7+
exclude: [
8+
'test/fixtures',
9+
'run',
10+
],
11+
devdep: [
12+
'egg-bin',
13+
'sequelize-cli',
14+
],
15+
dep: [
16+
'egg',
17+
'egg-sequelize',
18+
'mysql2',
19+
],
20+
semver: [
21+
],
22+
};

sequelize-example/.sequelizerc

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
3+
const path = require('path');
4+
5+
module.exports = {
6+
config: path.join(__dirname, 'database/config.json'),
7+
'migrations-path': path.join(__dirname, 'database/migrations'),
8+
'seeders-path': path.join(__dirname, 'database/seeders'),
9+
};

sequelize-example/README.md

+36-21
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,53 @@
11
# sequelize-example
22

3-
The [egg] example project that uses [egg-sequelize] plugin.
3+
The [egg] example project that uses [egg-sequelize] plugin. It will show you how to use sequelize in egg project, use [migrations] to help you manage changes of database and use [factory-girl] to help you write test cases more maintainable.
44

55
## QuickStart
66

7-
<!-- add docs here for user -->
7+
### Dependencies
88

9-
see [egg docs][egg] for more detail.
9+
- install mysql and create database
1010

11-
### Development
12-
```bash
13-
$ npm install
14-
$ createdb example-dev --owner postgres
15-
$ npm run migrate:up
16-
$ npm run dev
17-
$ open http://localhost:7001/users
1811
```
12+
brew install mysql # macOS
13+
brew service start mysql
1914
20-
### Deploy
15+
mysql
16+
> create database `egg-sequelize-example-dev`;
17+
> create database `egg-sequelize-example-unittest`;
18+
```
19+
20+
- install dependencies
21+
22+
```
23+
npm install
24+
```
25+
26+
### Start Server and Run Test
2127

22-
Use `EGG_SERVER_ENV=prod` to enable prod mode
28+
- prepare database structure
2329

24-
```bash
25-
$ createdb example-prod --owner postgres
26-
$ NODE_ENV=production npm run migrate:up
27-
$ EGG_SERVER_ENV=prod npm start
2830
```
31+
# for develop
32+
npm run sequelize -- db:migrate
33+
# for unittest
34+
NODE_ENV=test npm run sequelize -- db:migrate
35+
```
36+
37+
- start project
2938

30-
### npm scripts
39+
```
40+
npm run dev
41+
```
3142

32-
- Use `npm run lint` to check code style.
33-
- Use `npm test` to run unit test.
34-
- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
43+
- run test
3544

45+
```
46+
npm test
47+
```
3648

3749
[egg]: https://eggjs.org
38-
[egg-sequelize]: https://github.com/eggjs/egg-sequelize
50+
[egg-sequelize]: https://github.com/eggjs/egg-sequelize
51+
[sequelize]: http://docs.sequelizejs.com/
52+
[migrations]: http://docs.sequelizejs.com/manual/tutorial/migrations.html
53+
[factory-girl]: https://github.com/aexmachina/factory-girl

sequelize-example/README.zh-CN.md

+36-26
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,53 @@
11
# sequelize-example
22

3-
使用 [egg-sequelize] 插件的 [egg] 示例项目
3+
这个 [egg] 示例项目示范如何使用 [egg-sequelize] 插件。它会展示如何在 egg 项目中使用 [sequelize] 连接数据库,使用 [migrations] 来管理数据结构变更,并通过 [factory-girl] 来编写更易于维护的测试用例
44

5-
## 快速入门
5+
## 快速开始
66

7-
<!-- 在此次添加使用文档 -->
7+
### 安装依赖
88

9-
如需进一步了解,参见 [egg 文档][egg]
9+
- 安装 mysql 并建立数据库
1010

11-
### 本地开发
12-
```bash
13-
$ npm install
14-
$ createdb example-dev --owner postgres
15-
$ npm run migrate:up
16-
$ npm run dev
17-
$ open http://localhost:7001/users
1811
```
12+
brew install mysql # macOS
13+
brew service start mysql
1914
20-
### 部署
15+
mysql
16+
> create database `egg-sequelize-example-dev`;
17+
> create database `egg-sequelize-example-unittest`;
18+
```
2119

22-
线上正式环境用 `EGG_SERVER_ENV=prod` 来启动。
20+
- 安装 node 依赖
2321

24-
```bash
25-
$ createdb example-prod --owner postgres
26-
$ NODE_ENV=production npm run migrate:up
27-
$ EGG_SERVER_ENV=prod npm start
2822
```
23+
npm install
24+
```
25+
26+
### 启动和测试
2927

30-
### 单元测试
31-
- [egg-bin] 内置了 [mocha], [thunk-mocha], [power-assert], [istanbul] 等框架,让你可以专注于写单元测试,无需理会配套工具。
32-
- 断言库非常推荐使用 [power-assert]
33-
- 具体参见 [egg 文档 -单元测试](https://eggjs.org/zh-cn/core/unittest)
28+
- 执行 migration 执行数据变更
3429

35-
### 内置指令
30+
```
31+
# for develop
32+
npm run sequelize -- db:migrate
33+
# for unittest
34+
NODE_ENV=test npm run sequelize -- db:migrate
35+
```
3636

37-
- 使用 `npm run lint` 来做代码风格检查。
38-
- 使用 `npm test` 来执行单元测试。
39-
- 使用 `npm run autod` 来自动检测依赖更新,详细参见 [autod](https://www.npmjs.com/package/autod)
37+
- 启动项目
4038

39+
```
40+
npm run dev
41+
```
42+
43+
- 运行测试
44+
45+
```
46+
npm test
47+
```
4148

4249
[egg]: https://eggjs.org
43-
[egg-sequelize]: https://github.com/eggjs/egg-sequelize
50+
[egg-sequelize]: https://github.com/eggjs/egg-sequelize
51+
[sequelize]: http://docs.sequelizejs.com/
52+
[migrations]: http://docs.sequelizejs.com/manual/tutorial/migrations.html
53+
[factory-girl]: https://github.com/aexmachina/factory-girl

sequelize-example/app/controller/post.js

+19-14
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,42 @@
33
const Controller = require('egg').Controller;
44

55
class PostController extends Controller {
6-
async posts() {
6+
async index() {
77
const ctx = this.ctx;
8-
ctx.body = await ctx.service.post.list(ctx.query);
8+
const query = {
9+
limit: ctx.helper.parseInt(ctx.query.limit),
10+
offset: ctx.helper.parseInt(ctx.query.offset),
11+
};
12+
ctx.body = await ctx.service.post.list(query);
913
}
1014

11-
async post() {
15+
async show() {
1216
const ctx = this.ctx;
13-
ctx.body = await ctx.service.post.find(ctx.params.id);
17+
ctx.body = await ctx.service.post.find(ctx.helper.parseInt(ctx.params.id));
1418
}
1519

1620
async create() {
1721
const ctx = this.ctx;
18-
const body = ctx.request.body;
19-
body.user_id = +ctx.params.user_id;
20-
const created = await ctx.service.post.create(ctx.request.body);
22+
const post = await ctx.service.post.create(ctx.request.body);
2123
ctx.status = 201;
22-
ctx.body = created;
24+
ctx.body = post;
2325
}
2426

2527
async update() {
2628
const ctx = this.ctx;
2729
const id = ctx.params.id;
28-
const user_id = +ctx.params.user_id;
29-
const body = ctx.request.body;
30-
ctx.body = await ctx.service.post.update({ id, user_id, updates: body });
30+
const updates = {
31+
title: ctx.request.body.title,
32+
content: ctx.request.body.content,
33+
};
34+
ctx.body = await ctx.service.post.update({ id, user_id: ctx.request.body.user_id, updates });
3135
}
3236

33-
async del() {
37+
async destroy() {
3438
const ctx = this.ctx;
35-
const id = ctx.params.id;
36-
await ctx.service.post.del(id);
39+
const id = ctx.helper.parseInt(ctx.params.id);
40+
const user_id = ctx.helper.parseInt(ctx.request.body.user_id);
41+
await ctx.service.post.destroy({ id, user_id });
3742
ctx.status = 200;
3843
}
3944
}

sequelize-example/app/controller/user.js

+13-9
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,37 @@
33
const Controller = require('egg').Controller;
44

55
class UserController extends Controller {
6-
async users() {
6+
async index() {
77
const ctx = this.ctx;
8-
ctx.body = await ctx.service.user.list(ctx.query);
8+
const query = {
9+
limit: ctx.helper.parseInt(ctx.query.limit),
10+
offset: ctx.helper.parseInt(ctx.query.offset),
11+
};
12+
ctx.body = await ctx.service.user.list(query);
913
}
1014

11-
async user() {
15+
async show() {
1216
const ctx = this.ctx;
13-
ctx.body = await ctx.service.user.find(ctx.params.id);
17+
ctx.body = await ctx.service.user.find(ctx.helper.parseInt(ctx.params.id));
1418
}
1519

1620
async create() {
1721
const ctx = this.ctx;
18-
const created = await ctx.service.user.create(ctx.request.body);
22+
const user = await ctx.service.user.create(ctx.request.body);
1923
ctx.status = 201;
20-
ctx.body = created;
24+
ctx.body = user;
2125
}
2226

2327
async update() {
2428
const ctx = this.ctx;
25-
const id = ctx.params.id;
29+
const id = ctx.helper.parseInt(ctx.params.id);
2630
const body = ctx.request.body;
2731
ctx.body = await ctx.service.user.update({ id, updates: body });
2832
}
2933

30-
async del() {
34+
async destroy() {
3135
const ctx = this.ctx;
32-
const id = ctx.params.id;
36+
const id = ctx.helper.parseInt(ctx.params.id);
3337
await ctx.service.user.del(id);
3438
ctx.status = 200;
3539
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
3+
module.exports = {
4+
parseInt(string) {
5+
if (typeof string === 'number') return string;
6+
if (!string) return string;
7+
return parseInt(string) || 0;
8+
},
9+
};

sequelize-example/app/model/post.js

+6
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,11 @@ module.exports = app => {
2020
app.model.Post.belongsTo(app.model.User, { as: 'user', foreignKey: 'user_id' });
2121
};
2222

23+
Post.findByIdWithUser = async function(id, userId) {
24+
return await this.findOne({
25+
where: { id, user_id: userId },
26+
});
27+
};
28+
2329
return Post;
2430
};

sequelize-example/app/model/user.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ module.exports = app => {
1616
});
1717

1818
User.prototype.associate = function() {
19-
app.model.User.hasMany(app.model.Post, { as: 'posts', foreignKey: 'user_id' });
19+
app.model.User.hasMany(app.model.Post, { as: 'posts' });
2020
};
2121

2222
return User;

sequelize-example/app/router.js

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
11
'use strict';
22

33
module.exports = app => {
4-
app.router.get('/users', 'user.users');
5-
app.router.get('/users/:id', 'user.user');
6-
app.router.post('/users', 'user.create');
7-
app.router.put('/users/:id', 'user.update');
8-
app.del('/users/:id', 'user.del');
9-
10-
app.router.get('/posts', 'post.posts');
11-
app.router.get('/posts/:id', 'post.post');
12-
app.router.post('/users/:user_id/posts', 'post.create');
13-
app.router.put('/users/:user_id/posts/:id', 'post.update');
14-
app.del('/users/:user_id/posts/:id', 'post.del');
4+
app.resources('users', '/users', app.controller.user);
5+
app.resources('posts', '/posts', app.controller.post);
156
};

0 commit comments

Comments
 (0)