Skip to content

Commit faea8e6

Browse files
egg
1 parent b9ad292 commit faea8e6

36 files changed

+11570
-0
lines changed

17-nodejs/02-egg/.autod.conf.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
module.exports = {
4+
write: true,
5+
plugin: 'autod-egg',
6+
prefix: '^',
7+
devprefix: '^',
8+
exclude: [
9+
'test/fixtures',
10+
'coverage',
11+
],
12+
dep: [
13+
'egg',
14+
'egg-scripts',
15+
],
16+
devdep: [
17+
'autod',
18+
'autod-egg',
19+
'egg-bin',
20+
'tslib',
21+
'typescript',
22+
],
23+
keep: [
24+
],
25+
semver: [
26+
],
27+
test: 'scripts',
28+
};

17-nodejs/02-egg/.eslintignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
**/*.d.ts
2+
node_modules/

17-nodejs/02-egg/.eslintrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"extends": "eslint-config-egg/typescript",
3+
"parserOptions": {
4+
"project": "./tsconfig.json"
5+
}
6+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
2+
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3+
4+
name: Node.js CI
5+
6+
on:
7+
push:
8+
branches: [ master ]
9+
pull_request:
10+
branches: [ master ]
11+
12+
jobs:
13+
build:
14+
15+
runs-on: ${{ matrix.os }}
16+
17+
strategy:
18+
matrix:
19+
node-version: [8.x]
20+
os: [ubuntu-latest, windows-latest, macos-latest]
21+
22+
steps:
23+
- uses: actions/checkout@v2
24+
- name: Use Node.js ${{ matrix.node-version }}
25+
uses: actions/setup-node@v1
26+
with:
27+
node-version: ${{ matrix.node-version }}
28+
- run: npm i -g npminstall && npminstall
29+
- run: npm run ci
30+
env:
31+
CI: true

17-nodejs/02-egg/.gitignore

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
logs/
2+
npm-debug.log
3+
node_modules/
4+
coverage/
5+
.idea/
6+
run/
7+
logs/
8+
.DS_Store
9+
.vscode
10+
*.swp
11+
*.lock
12+
*.js
13+
!.autod.conf.js
14+
15+
app/**/*.js
16+
test/**/*.js
17+
config/**/*.js
18+
app/**/*.map
19+
test/**/*.map
20+
config/**/*.map

17-nodejs/02-egg/.travis.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
language: node_js
3+
node_js:
4+
- '8'
5+
before_install:
6+
- npm i npminstall -g
7+
install:
8+
- npminstall
9+
script:
10+
- npm run ci
11+
after_script:
12+
- npminstall codecov && codecov

17-nodejs/02-egg/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# hackernews-async-ts
2+
3+
[Hacker News](https://news.ycombinator.com/) showcase using typescript && egg
4+
5+
## QuickStart
6+
7+
### Development
8+
9+
```bash
10+
$ npm i
11+
$ npm run dev
12+
$ open http://localhost:7001/
13+
```
14+
15+
Don't tsc compile at development mode, if you had run `tsc` then you need to `npm run clean` before `npm run dev`.
16+
17+
### Deploy
18+
19+
```bash
20+
$ npm run tsc
21+
$ npm start
22+
```
23+
24+
### Npm Scripts
25+
26+
- Use `npm run lint` to check code style
27+
- Use `npm test` to run unit test
28+
- se `npm run clean` to clean compiled js at development mode once
29+
30+
### Requirement
31+
32+
- Node.js 8.x
33+
- Typescript 2.8+

17-nodejs/02-egg/app.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class AppBootHook {
2+
private app;
3+
constructor(app) {
4+
this.app = app;
5+
}
6+
7+
configWillLoad() {
8+
// 此时 config 文件已经被读取并合并,但是还并未生效
9+
// 这是应用层修改配置的最后时机
10+
// 注意:此函数只支持同步调用
11+
12+
// 例如:参数中的密码是加密的,在此处进行解密
13+
// this.app.config.mysql.password = decrypt(this.app.config.mysql.password);
14+
// 例如:插入一个中间件到框架的 coreMiddleware 之间
15+
// const statusIdx = this.app.config.coreMiddleware.indexOf('status');
16+
// this.app.config.coreMiddleware.splice(statusIdx + 1, 0, 'limit');
17+
}
18+
19+
async didLoad() {
20+
// 所有的配置已经加载完毕
21+
// 可以用来加载应用自定义的文件,启动自定义的服务
22+
23+
// 例如:创建自定义应用的示例
24+
// this.app.queue = new Queue(this.app.config.queue);
25+
// await this.app.queue.init();
26+
27+
// 例如:加载自定义的目录
28+
// this.app.loader.loadToContext(path.join(__dirname, 'app/tasks'), 'tasks', {
29+
// fieldClass: 'tasksClasses',
30+
// });
31+
}
32+
33+
async willReady() {
34+
// 所有的插件都已启动完毕,但是应用整体还未 ready
35+
// 可以做一些数据初始化等操作,这些操作成功才会启动应用
36+
37+
// 例如:从数据库加载数据到内存缓存
38+
// this.app.cacheData = await this.app.model.query(QUERY_CACHE_SQL);
39+
}
40+
41+
async didReady() {
42+
// 应用已经启动完毕
43+
44+
// const ctx = await this.app.createAnonymousContext();
45+
// await ctx.service.Biz.request();
46+
}
47+
48+
async serverDidReady() {
49+
console.log('app start');
50+
// http / https server 已启动,开始接受外部请求
51+
// 此时可以从 app.server 拿到 server 的实例
52+
53+
this.app.server.on('timeout', socket => {
54+
// handle socket timeout
55+
console.log(socket.connecting);
56+
});
57+
}
58+
}
59+
60+
export default AppBootHook;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Controller } from 'egg';
2+
3+
export default class HomeController extends Controller {
4+
public async index() {
5+
const { ctx } = this;
6+
ctx.body = await ctx.service.test.sayHi('egg');
7+
}
8+
public async notFound() {
9+
const { ctx } = this;
10+
ctx.body = '404~~~~';
11+
}
12+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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 TopicController extends Controller {
11+
// GET /topics topics
12+
public async index() {
13+
const { ctx } = this;
14+
ctx.body = ctx.app.env; // local
15+
ctx.response.type = 'application/json';
16+
ctx.status = 200;
17+
}
18+
19+
// GET /topics/new new_topic
20+
public async new() {
21+
const { app, ctx } = this;
22+
ctx.throw({
23+
code: app.config.CODE.TEST_ERROR,
24+
message: '测试错误抛出',
25+
});
26+
}
27+
28+
// POST /topics topics
29+
public async create() {
30+
const { ctx } = this;
31+
// 校验 `ctx.request.body` 是否符合我们预期的格式
32+
// 如果参数校验未通过,将会抛出一个 status = 422 的异常
33+
ctx.validate(createRule, ctx.request.body);
34+
// 调用 service 创建一个 topic
35+
const data = await ctx.service.topics.create(ctx.request.body);
36+
// 设置响应体和状态码
37+
ctx.helper.rest({
38+
...data
39+
}, 'ok', 0);
40+
}
41+
// GET /topics/:id topic
42+
public async show() {}
43+
// GET /topics/:id/edit edit_topic
44+
public async edit() {}
45+
// PUT /topics/:id topic
46+
public async update() {}
47+
// DELETE /topics/:id topic
48+
public async destroy() {}
49+
}

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @name: rest.js
3+
* @desc: restful middleware
4+
* @author: [email protected]
5+
* @date: 2020.07.13
6+
*/
7+
import { IHelper } from 'egg';
8+
9+
export default {
10+
async rest(this: IHelper, data = {}, message = 'success', code = 0) {
11+
const { ctx } = this;
12+
ctx.response.type = 'application/json';
13+
ctx.response.body = {
14+
code,
15+
message,
16+
data,
17+
};
18+
}
19+
};
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
export default () => {
2+
return async function errorHandler(ctx, next) {
3+
try {
4+
await next();
5+
} catch (err) {
6+
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
7+
ctx.app.emit('error', err, ctx);
8+
9+
const status = err.status || 500;
10+
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
11+
const error = status === 500 && ctx.app.config.env === 'prod'
12+
? 'Internal Server Error'
13+
: err.message;
14+
15+
// 从 error 对象上读出各个属性,设置到响应中
16+
ctx.body = {
17+
code: parseInt(err.code) || -1,
18+
message: error,
19+
};
20+
switch (status) {
21+
// 参数校验未通过
22+
case 422:
23+
ctx.body.detail = err.errors;
24+
break;
25+
}
26+
ctx.status = status;
27+
}
28+
29+
// 404 单独处理
30+
if (ctx.status === 404 && !ctx.body) {
31+
console.log(ctx.acceptJSON)
32+
if (ctx.acceptJSON) {
33+
ctx.body = { error: 'Not Found' };
34+
} else {
35+
ctx.body = '<h1>Page Not Found</h1>';
36+
}
37+
}
38+
};
39+
};
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
3+
// options === app.config.robot
4+
export default (options, app) => {
5+
console.log(app.config.robot);
6+
return async function robotMiddleware(ctx, next) {
7+
const source = ctx.get('user-agent') || '';
8+
const match = options.ua.some(ua => ua.test(source));
9+
if (match) {
10+
ctx.status = 403;
11+
ctx.message = 'Go away, robot.';
12+
} else {
13+
await next();
14+
}
15+
}
16+
};

17-nodejs/02-egg/app/public/test.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<h1>test html</h1>

17-nodejs/02-egg/app/router.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Application } from 'egg';
2+
3+
export default (app: Application) => {
4+
const { controller, router } = app;
5+
6+
router.get('/', controller.index.index);
7+
router.resources('topics', '/api/topics', app.controller.topics);
8+
router.get('*', controller.index.notFound);
9+
10+
};

17-nodejs/02-egg/app/service/Test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { Service } from 'egg';
2+
3+
/**
4+
* Test Service
5+
*/
6+
export default class Test extends Service {
7+
8+
/**
9+
* sayHi to you
10+
* @param name - your name
11+
*/
12+
public async sayHi(name: string) {
13+
return `hi, ${name}`;
14+
}
15+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Service } from 'egg';
2+
3+
export default class TopicService extends Service {
4+
constructor(ctx) {
5+
super(ctx);
6+
}
7+
8+
public async create(params) {
9+
return params;
10+
}
11+
}

17-nodejs/02-egg/appveyor.yml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
environment:
2+
matrix:
3+
- nodejs_version: '8'
4+
5+
install:
6+
- ps: Install-Product node $env:nodejs_version
7+
- npm i npminstall && node_modules\.bin\npminstall
8+
9+
test_script:
10+
- node --version
11+
- npm --version
12+
- npm run test
13+
14+
build: off

0 commit comments

Comments
 (0)