Skip to content

Commit 8150b21

Browse files
egg-orm
1 parent faea8e6 commit 8150b21

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1579
-486
lines changed

17-nodejs/02-egg/.eslintignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
**/*.d.ts
22
node_modules/
3+
test/

17-nodejs/02-egg/.sequelizerc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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+
'models-path': path.join(__dirname, 'app/model'),
10+
};

17-nodejs/02-egg/LICENSE

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
MIT LICENSE

17-nodejs/02-egg/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,24 @@ $ npm start
3131

3232
- Node.js 8.x
3333
- Typescript 2.8+
34+
35+
36+
$ redis-server
37+
38+
redis
39+
seed
40+
docs
41+
cros
42+
TDD
43+
域名
44+
登录态
45+
权限校验
46+
whistle
47+
husky
48+
lint-staged
49+
prettier
50+
51+
52+
sequelize
53+
https://sequelize.org/master/manual/query-interface.html
54+
https://sequelize.org/master/variable/index.html#static-variable-DataTypes

17-nodejs/02-egg/app.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,4 @@ class AppBootHook {
5757
}
5858
}
5959

60-
export default AppBootHook;
60+
export default AppBootHook;
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { Controller } from 'egg';
2+
3+
// 定义创建接口的请求参数规则
4+
// https://github.com/node-modules/parameter#rule
5+
const createRule = {
6+
name: 'string',
7+
type: { type: 'enum', values: [ 'ask', 'share' ], required: false },
8+
};
9+
10+
export default class DemoController extends Controller {
11+
// GET /demo
12+
public async index() {
13+
const { ctx } = this;
14+
ctx.logger.debug('test logger');
15+
ctx.body = `<h1>${ctx.app.env}</h1>`; // local
16+
ctx.response.type = 'text/html';
17+
ctx.status = 200;
18+
19+
// ctx.app.redis.get()
20+
// client.on('connect', function () {
21+
// // set 语法
22+
// client.set('lubanH5makerTest', 'csxiaoyao', function (err, data) {
23+
// console.log(1, data)
24+
// })
25+
// // get 语法
26+
// client.get('lubanH5makerTest', function (err, data) {
27+
// console.log(2, data)
28+
// })
29+
// })
30+
}
31+
32+
// GET /demo/new
33+
public async new() {
34+
const { app, ctx } = this;
35+
ctx.throw({
36+
code: app.config.CODE.TEST_ERROR,
37+
message: '测试错误抛出',
38+
});
39+
}
40+
41+
// POST /demo
42+
public async create() {
43+
const { ctx } = this;
44+
// 校验 `ctx.request.body` 是否符合我们预期的格式
45+
// 如果参数校验未通过,将会抛出一个 status = 422 的异常
46+
ctx.validate(createRule, ctx.request.body);
47+
// 调用 service 创建一个 demo
48+
const data = await ctx.service.demo.create(ctx.request.body);
49+
// 设置响应体和状态码
50+
ctx.helper.rest({
51+
...data,
52+
}, 'ok', 0);
53+
}
54+
// GET /demo/:id
55+
public async show() {
56+
const { ctx } = this;
57+
ctx.logger.debug('fetch id: %j', ctx.params.id);
58+
console.log('test show');
59+
}
60+
// GET /demo/:id/edit edit_demo
61+
public async edit() {
62+
console.log('test edit');
63+
}
64+
// PUT /demo/:id demo
65+
public async update() {
66+
console.log('test update');
67+
}
68+
// DELETE /demo/:id demo
69+
public async destroy() {
70+
console.log('test destroy');
71+
}
72+
}

17-nodejs/02-egg/app/controller/index.ts

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { Controller } from 'egg';
2+
3+
export default class PostController extends Controller {
4+
// GET /api/posts?limit=5&offset=5 6~10
5+
public async index() {
6+
const ctx = this.ctx;
7+
const query = {
8+
limit: parseInt(ctx.query.limit) || 10,
9+
offset: parseInt(ctx.query.offset) || 0,
10+
};
11+
const data = await ctx.service.post.list(query);
12+
ctx.helper.rest({
13+
...data, // { "count": 2, "rows": [{...}, {...}] }
14+
});
15+
}
16+
17+
// GET /api/posts/:id
18+
public async show() {
19+
const ctx = this.ctx;
20+
const data = await ctx.service.post.find(parseInt(ctx.params.id) || 0);
21+
ctx.helper.rest(data); // {...}
22+
}
23+
24+
// POST /api/posts
25+
public async create() {
26+
const ctx = this.ctx;
27+
const createRule = {
28+
title: 'string',
29+
content: 'string',
30+
user_id: 'int',
31+
};
32+
const body = ctx.request.body;
33+
ctx.validate(createRule, body);
34+
const data = await ctx.service.post.create(body);
35+
ctx.helper.rest(data); // {...}
36+
ctx.status = 201;
37+
}
38+
39+
// PUT /api/posts/:id
40+
public async update() {
41+
const ctx = this.ctx;
42+
const id = parseInt(ctx.params.id) || 0;
43+
const updates = {
44+
user_id: ctx.request.body.user_id,
45+
title: ctx.request.body.title,
46+
content: ctx.request.body.content,
47+
};
48+
const updateRule = {
49+
user_id: { type: 'int', required: false },
50+
title: { type: 'string', required: false },
51+
content: { type: 'string', required: false },
52+
};
53+
ctx.validate(updateRule, updates);
54+
const data = await ctx.service.post.update({ id, user_id: updates.user_id, updates });
55+
ctx.helper.rest(data); // {...}
56+
}
57+
58+
// DELETE /api/posts/:id
59+
public async destroy() {
60+
const ctx = this.ctx;
61+
const id = parseInt(ctx.params.id) || 0;
62+
const user_id = parseInt(ctx.request.body.user_id);
63+
await ctx.service.post.destroy({ id, user_id });
64+
ctx.helper.rest({ id, user_id });
65+
}
66+
}

17-nodejs/02-egg/app/controller/topics.ts

Lines changed: 0 additions & 49 deletions
This file was deleted.
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { Controller } from 'egg';
2+
3+
export default class UserController extends Controller {
4+
// GET /api/users?limit=5&offset=5 6~10
5+
public async index() {
6+
const { ctx } = this;
7+
const query = {
8+
limit: parseInt(ctx.query.limit) || 10,
9+
offset: parseInt(ctx.query.offset) || 0,
10+
};
11+
const data = await ctx.service.user.list(query);
12+
ctx.helper.rest({
13+
...data, // { "count": 2, "rows": [{...}, {...}] }
14+
}, 'ok', 0);
15+
}
16+
17+
// GET /api/users/:id
18+
public async show() {
19+
const ctx = this.ctx;
20+
const data = await ctx.service.user.find(parseInt(ctx.params.id) || 0);
21+
ctx.helper.rest(data); // {...}
22+
}
23+
24+
// POST /api/users
25+
public async create() {
26+
const { ctx } = this;
27+
// 参数校验 `ctx.request.body` 未通过将抛出 status = 422 的异常
28+
// https://github.com/node-modules/parameter#rule
29+
const createRule = {
30+
name: 'string',
31+
age: 'int',
32+
gender: { type: 'enum', values: [ 'male', 'female', 'unknown' ], required: false },
33+
// createdAt: { type: 'datetime', required: false },
34+
// updatedAt: { type: 'datetime', required: false },
35+
};
36+
const body = ctx.request.body;
37+
ctx.validate(createRule, body);
38+
const data = await ctx.service.user.create(body);
39+
ctx.helper.rest(data); // {...}
40+
ctx.status = 201;
41+
}
42+
43+
// PUT /api/users/:id
44+
public async update() {
45+
const { ctx } = this;
46+
const id = parseInt(ctx.params.id) || 0;
47+
const updates = {
48+
name: ctx.request.body.name,
49+
age: ctx.request.body.age,
50+
gender: ctx.request.body.gender,
51+
// updatedAt: new Date(),
52+
};
53+
const updateRule = {
54+
name: { type: 'string', required: false },
55+
age: { type: 'int', required: false },
56+
gender: { type: 'enum', values: [ 'male', 'female', 'unknown' ], required: false },
57+
};
58+
ctx.validate(updateRule, updates);
59+
const data = await ctx.service.user.update({ id, updates });
60+
ctx.helper.rest(data); // {...}
61+
}
62+
63+
// DELETE /api/users/:id
64+
public async destroy() {
65+
const { ctx } = this;
66+
const id = parseInt(ctx.params.id) || 0;
67+
await ctx.service.user.del(id);
68+
ctx.helper.rest({ id });
69+
}
70+
}

17-nodejs/02-egg/app/extend/helper.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ export default {
1515
message,
1616
data,
1717
};
18-
}
18+
},
1919
};

17-nodejs/02-egg/app/middleware/errorHandler.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,38 @@ export default () => {
66
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
77
ctx.app.emit('error', err, ctx);
88

9-
const status = err.status || 500;
9+
const code = parseInt(err.code) || -1;
10+
const status = err.status || (code >= 0 ? 400 : 500);
11+
1012
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
1113
const error = status === 500 && ctx.app.config.env === 'prod'
1214
? 'Internal Server Error'
1315
: err.message;
1416

1517
// 从 error 对象上读出各个属性,设置到响应中
1618
ctx.body = {
17-
code: parseInt(err.code) || -1,
19+
code,
1820
message: error,
1921
};
2022
switch (status) {
2123
// 参数校验未通过
2224
case 422:
2325
ctx.body.detail = err.errors;
2426
break;
27+
default:
28+
//
2529
}
2630
ctx.status = status;
2731
}
2832

2933
// 404 单独处理
3034
if (ctx.status === 404 && !ctx.body) {
31-
console.log(ctx.acceptJSON)
35+
console.log(ctx.acceptJSON);
3236
if (ctx.acceptJSON) {
3337
ctx.body = { error: 'Not Found' };
3438
} else {
3539
ctx.body = '<h1>Page Not Found</h1>';
3640
}
3741
}
3842
};
39-
};
43+
};

17-nodejs/02-egg/app/middleware/robot.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@ export default (options, app) => {
1212
} else {
1313
await next();
1414
}
15-
}
15+
};
1616
};

0 commit comments

Comments
 (0)