@@ -38,20 +38,20 @@ const Controller = require('egg').Controller
38
38
39
39
class PostController extends Controller {
40
40
async create () {
41
- const {ctx , service } = this
41
+ const { ctx , service } = this
42
42
const createRule = {
43
- title: {type: ' string' },
44
- content: {type: ' string' },
43
+ title: { type: ' string' },
44
+ content: { type: ' string' },
45
45
}
46
46
// 校验参数
47
47
ctx .validate (createRule)
48
48
// 组装参数
49
49
const author = ctx .session .userId
50
- const req = Object .assign (ctx .request .body , {author})
50
+ const req = Object .assign (ctx .request .body , { author })
51
51
// 调用 Service 进行业务处理
52
52
const res = await service .post .create (req)
53
53
// 设置响应内容和响应状态码
54
- ctx .body = {id: res .id }
54
+ ctx .body = { id: res .id }
55
55
ctx .status = 201
56
56
}
57
57
}
@@ -65,7 +65,7 @@ module.exports = PostController
65
65
``` js
66
66
// app/router.js
67
67
module .exports = (app ) => {
68
- const {router , controller } = app
68
+ const { router , controller } = app
69
69
router .post (' createPost' , ' /api/posts' , controller .post .create )
70
70
}
71
71
```
@@ -99,7 +99,7 @@ Controller 基类的方式封装应用中常用的方法。
99
99
100
100
``` js
101
101
// app/core/base_controller.js
102
- const {Controller } = require (' egg' )
102
+ const { Controller } = require (' egg' )
103
103
104
104
class BaseController extends Controller {
105
105
get user () {
@@ -144,18 +144,18 @@ class PostController extends Controller {
144
144
// app/controller/post.js
145
145
exports .create = async (ctx ) => {
146
146
const createRule = {
147
- title: {type: ' string' },
148
- content: {type: ' string' },
147
+ title: { type: ' string' },
148
+ content: { type: ' string' },
149
149
}
150
150
// 校验参数
151
151
ctx .validate (createRule)
152
152
// 组装参数
153
153
const author = ctx .session .userId
154
- const req = Object .assign (ctx .request .body , {author})
154
+ const req = Object .assign (ctx .request .body , { author })
155
155
// 调用 service 进行业务处理
156
156
const res = await ctx .service .post .create (req)
157
157
// 设置响应内容和响应状态码
158
- ctx .body = {id: res .id }
158
+ ctx .body = { id: res .id }
159
159
ctx .status = 201
160
160
}
161
161
```
@@ -208,8 +208,7 @@ if (key.startsWith('egg')) {
208
208
209
209
### Queries
210
210
211
- 有时候系统会设计成让用户传递相同的 ` key ` ,例如 ` GET /posts?category=egg&id=1&id=2&id=3 ` 。针对此类情况,\*
212
- \* 框架提供了 ` ctx.queries ` 对象,这个对象也解析了 ` Query String ` ,但是它不会丢弃任何一个重复的数据,而是将他们都放到一个数组中
211
+ 有时候系统会设计成让用户传递相同的 ` key ` ,例如 ` GET /posts?category=egg&id=1&id=2&id=3 ` 。针对此类情况,\* \* 框架提供了 ` ctx.queries ` 对象,这个对象也解析了 ` Query String ` ,但是它不会丢弃任何一个重复的数据,而是将他们都放到一个数组中
213
212
\*\* :
214
213
215
214
``` js
@@ -328,10 +327,9 @@ exports.multipart = {
328
327
前端上传代码示例:
329
328
330
329
``` html
331
-
332
330
<form method =" POST" action =" /upload?_csrf={{ ctx.csrf | safe }}" enctype =" multipart/form-data" >
333
- title: <input name =" title" /> file: <input name =" file" type =" file" />
334
- <button type =" submit" >Upload</button >
331
+ title: <input name =" title" /> file: <input name =" file" type =" file" />
332
+ <button type =" submit" >Upload</button >
335
333
</form >
336
334
```
337
335
@@ -344,14 +342,15 @@ const fs = require('mz/fs')
344
342
345
343
module .exports = class extends Controller {
346
344
async upload () {
347
- const {ctx } = this
345
+ const { ctx } = this
348
346
const file = ctx .request .files [0 ]
349
347
const name = ` egg-multipart-test/${ path .basename (file .filename )} `
350
348
let result
351
349
try {
352
350
// 处理文件,比如上传到云端
353
351
result = await ctx .oss .put (name, file .filepath )
354
- } finally {
352
+ }
353
+ finally {
355
354
// 需要删除临时文件
356
355
await fs .unlink (file .filepath )
357
356
}
@@ -366,17 +365,15 @@ module.exports = class extends Controller {
366
365
```
367
366
368
367
上面的是基于最简单的单个文件上传进行的代码示例,借助` ctx.request.files `
369
- 数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助` ctx.request.files ` 数组,\*
370
- \* 不过需要多注意一步——数组遍历\*\*
368
+ 数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助` ctx.request.files ` 数组,\* \* 不过需要多注意一步——数组遍历\*\*
371
369
372
370
前端多文件上传:
373
371
374
372
``` html
375
-
376
373
<form method =" POST" action =" /upload?_csrf={{ ctx.csrf | safe }}" enctype =" multipart/form-data" >
377
- title: <input name =" title" /> file1: <input name =" file1" type =" file" /> file2:
378
- <input name =" file2" type =" file" />
379
- <button type =" submit" >Upload</button >
374
+ title: <input name =" title" /> file1: <input name =" file1" type =" file" /> file2:
375
+ <input name =" file2" type =" file" />
376
+ <button type =" submit" >Upload</button >
380
377
</form >
381
378
```
382
379
@@ -389,7 +386,7 @@ const fs = require('mz/fs')
389
386
390
387
module .exports = class extends Controller {
391
388
async upload () {
392
- const {ctx } = this
389
+ const { ctx } = this
393
390
console .log (ctx .request .body )
394
391
console .log (' got %d files' , ctx .request .files .length )
395
392
// 遍历文件
@@ -403,7 +400,8 @@ module.exports = class extends Controller {
403
400
try {
404
401
// 处理文件,比如上传到云端
405
402
result = await ctx .oss .put (` egg-multipart-test/${ file .filename } ` , file .filepath )
406
- } finally {
403
+ }
404
+ finally {
407
405
// 需要删除临时文件
408
406
await fs .unlink (file .filepath )
409
407
}
@@ -423,10 +421,9 @@ module.exports = class extends Controller {
423
421
前端示例:
424
422
425
423
``` html
426
-
427
424
<form method =" POST" action =" /upload?_csrf={{ ctx.csrf | safe }}" enctype =" multipart/form-data" >
428
- title: <input name =" title" /> file: <input name =" file" type =" file" />
429
- <button type =" submit" >Upload</button >
425
+ title: <input name =" title" /> file: <input name =" file" type =" file" />
426
+ <button type =" submit" >Upload</button >
430
427
</form >
431
428
```
432
429
@@ -446,7 +443,8 @@ class UploaderController extends Controller {
446
443
let result
447
444
try {
448
445
result = await ctx .oss .put (name, stream)
449
- } catch (err) {
446
+ }
447
+ catch (err) {
450
448
// 必须将上传的文件流消费掉,要不然浏览器响应会卡死
451
449
await sendToWormhole (stream)
452
450
throw err
@@ -489,7 +487,8 @@ class UploaderController extends Controller {
489
487
console .log (` value: ${ part[1 ]} ` )
490
488
console .log (` valueTruncated: ${ part[2 ]} ` )
491
489
console .log (` fieldnameTruncated: ${ part[3 ]} ` )
492
- } else {
490
+ }
491
+ else {
493
492
if (! part .filename ) {
494
493
// 这时是用户没有选择文件就点击了上传(part 是 file stream,但是 part.filename 为空)
495
494
// 需要做出处理,例如给出错误提示消息
@@ -504,7 +503,8 @@ class UploaderController extends Controller {
504
503
let result
505
504
try {
506
505
result = await ctx .oss .put (` egg-multipart-test/${ part .filename } ` , part)
507
- } catch (err) {
506
+ }
507
+ catch (err) {
508
508
// 必须将上传的文件流消费掉,要不然浏览器响应会卡死
509
509
await sendToWormhole (part)
510
510
throw err
@@ -522,29 +522,29 @@ module.exports = UploaderController
522
522
** 为了保证文件上传的安全,框架限制了支持的的文件格式,框架默认支持白名单**
523
523
524
524
``` js
525
- // images
525
+ // images
526
526
' .jpg' , ' .jpeg' , // image/jpeg
527
- ' .png' , // image/png, image/x-png
528
- ' .gif' , // image/gif
529
- ' .bmp' , // image/bmp
530
- ' .wbmp' , // image/vnd.wap.wbmp
531
- ' .webp' ,
532
- ' .tif' ,
533
- ' .psd' ,
527
+ ' .png' , // image/png, image/x-png
528
+ ' .gif' , // image/gif
529
+ ' .bmp' , // image/bmp
530
+ ' .wbmp' , // image/vnd.wap.wbmp
531
+ ' .webp' ,
532
+ ' .tif' ,
533
+ ' .psd' ,
534
534
// text
535
- ' .svg' ,
536
- ' .js' , ' .jsx' ,
537
- ' .json' ,
538
- ' .css' , ' .less' ,
539
- ' .html' , ' .htm' ,
540
- ' .xml' ,
535
+ ' .svg' ,
536
+ ' .js' , ' .jsx' ,
537
+ ' .json' ,
538
+ ' .css' , ' .less' ,
539
+ ' .html' , ' .htm' ,
540
+ ' .xml' ,
541
541
// tar
542
- ' .zip' ,
543
- ' .gz' , ' .tgz' , ' .gzip' ,
542
+ ' .zip' ,
543
+ ' .gz' , ' .tgz' , ' .gzip' ,
544
544
// video
545
- ' .mp3' ,
546
- ' .mp4' ,
547
- ' .avi'
545
+ ' .mp3' ,
546
+ ' .mp4' ,
547
+ ' .avi'
548
548
```
549
549
550
550
用户可以通过在 ` config/config.default.js ` 中配置** 来新增支持的文件扩展名,或者重写整个白名单**
@@ -600,8 +600,7 @@ module.exports = {
600
600
601
601
通过这个 ` Getter ` 获取 ` protocol ` 时,首先会判断当前连接是否是加密连接,如果是加密连接,返回 ` https ` 。
602
602
603
- 如果处于非加密连接时,优先读通过 ` config.protocolHeaders ` 中配置的 header 的值来判断是 HTTP 还是 ` https ` ,\*
604
- \* 如果读取不到,可以在配置中通过 config.protocol 来设置兜底值,默认为 HTTP。\*\*
603
+ 如果处于非加密连接时,优先读通过 ` config.protocolHeaders ` 中配置的 header 的值来判断是 HTTP 还是 ` https ` ,\* \* 如果读取不到,可以在配置中通过 config.protocol 来设置兜底值,默认为 HTTP。\*\*
605
604
606
605
` config.protocolHeaders ` 默认配置为 ` x-forwarded-proto ` 。
607
606
@@ -631,7 +630,7 @@ HTTP 请求都是无状态的,但是 `Web` 应用通常都需要知道发起
631
630
class CookieController extends Controller {
632
631
// 添加cookies
633
632
async add () {
634
- const {ctx } = this
633
+ const { ctx } = this
635
634
let count = ctx .cookies .get (' count' )
636
635
count = count ? Number (count) : 0
637
636
ctx .cookies .set (' count' , ++ count)
@@ -640,7 +639,7 @@ class CookieController extends Controller {
640
639
641
640
// 删除cookies
642
641
async remove () {
643
- const {ctx } = this
642
+ const { ctx } = this
644
643
const count = ctx .cookies .set (' count' , null )
645
644
ctx .status = 204
646
645
}
@@ -660,7 +659,7 @@ class CookieController extends Controller {
660
659
``` js
661
660
class PostController extends Controller {
662
661
async fetchPosts () {
663
- const {ctx } = this
662
+ const { ctx } = this
664
663
// 获取 Session 上的内容
665
664
const userId = ctx .session .userId
666
665
const posts = await ctx .service .post .fetch (userId)
@@ -704,8 +703,8 @@ class PostController extends Controller {
704
703
// 校验参数
705
704
// 如果不传第二个参数会自动校验 `ctx.request.body`
706
705
this .ctx .validate ({
707
- title: {type: ' string' },
708
- content: {type: ' string' },
706
+ title: { type: ' string' },
707
+ content: { type: ' string' },
709
708
})
710
709
}
711
710
}
@@ -720,9 +719,10 @@ class PostController extends Controller {
720
719
const ctx = this .ctx
721
720
try {
722
721
ctx .validate (createRule)
723
- } catch (err) {
722
+ }
723
+ catch (err) {
724
724
ctx .logger .warn (err .errors )
725
- ctx .body = {success: false }
725
+ ctx .body = { success: false }
726
726
}
727
727
}
728
728
};
@@ -737,7 +737,8 @@ class PostController extends Controller {
737
737
app .validator .addRule (' json' , (rule , value ) => {
738
738
try {
739
739
JSON .parse (value)
740
- } catch (err) {
740
+ }
741
+ catch (err) {
741
742
return ' must be json string'
742
743
}
743
744
})
@@ -748,9 +749,9 @@ app.validator.addRule('json', (rule, value) => {
748
749
``` js
749
750
class PostController extends Controller {
750
751
async handler () {
751
- const {ctx } = this
752
+ const { ctx } = this
752
753
// query.test 字段必须是 json 字符串
753
- const rule = {test: ' json' }
754
+ const rule = { test: ' json' }
754
755
ctx .validate (rule, ctx .query )
755
756
}
756
757
};
@@ -767,13 +768,13 @@ class PostController extends Controller {
767
768
``` js
768
769
class PostController extends Controller {
769
770
async create () {
770
- const {ctx } = this
771
+ const { ctx } = this
771
772
const author = ctx .session .userId
772
773
// Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
773
- const req = Object .assign (ctx .request .body , {author})
774
+ const req = Object .assign (ctx .request .body , { author })
774
775
// 调用 service 进行业务处理
775
776
const res = await ctx .service .post .create (req)
776
- ctx .body = {id: res .id }
777
+ ctx .body = { id: res .id }
777
778
ctx .status = 201
778
779
}
779
780
}
@@ -811,7 +812,7 @@ class PostController extends Controller {
811
812
``` js
812
813
class ViewController extends Controller {
813
814
async show () {
814
- const {ctx } = this
815
+ const { ctx } = this
815
816
ctx .body = {
816
817
name: ' egg' ,
817
818
category: ' framework' ,
@@ -832,7 +833,7 @@ body 设置成一个 Stream,并会同时处理好这个 Stream 上的错误事
832
833
``` js
833
834
class ProxyController extends Controller {
834
835
async proxy () {
835
- const {ctx } = this
836
+ const { ctx } = this
836
837
const result = await ctx .curl (url, {
837
838
streaming: true ,
838
839
})
@@ -852,7 +853,7 @@ class ProxyController extends Controller {
852
853
class HomeController extends Controller {
853
854
async index () {
854
855
const ctx = this .ctx
855
- await ctx .render (' home.tpl' , {name: ' egg' })
856
+ await ctx .render (' home.tpl' , { name: ' egg' })
856
857
// ctx.body = await ctx.renderString('hi, {{ name }}', { name: 'egg' });
857
858
}
858
859
};
@@ -916,9 +917,9 @@ exports.jsonp = {
916
917
``` js
917
918
// app/router.js
918
919
module .exports = (app ) => {
919
- const {router , controller , jsonp } = app
920
- router .get (' /api/posts/:id' , jsonp ({callback: ' callback' }), controller .posts .show )
921
- router .get (' /api/posts' , jsonp ({callback: ' cb' }), controller .posts .list )
920
+ const { router , controller , jsonp } = app
921
+ router .get (' /api/posts/:id' , jsonp ({ callback: ' callback' }), controller .posts .show )
922
+ router .get (' /api/posts' , jsonp ({ callback: ' cb' }), controller .posts .list )
922
923
}
923
924
```
924
925
0 commit comments