Skip to content

Commit

Permalink
Merge pull request #162 from 142vip/feat/del-exec
Browse files Browse the repository at this point in the history
feat: 移除`exec`脚本执行器,修改`bundle`脚本逻辑
  • Loading branch information
微信公众号:储凡 authored Sep 19, 2024
2 parents c014fd4 + 05f7fa1 commit c92a53c
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 179 deletions.
145 changes: 73 additions & 72 deletions docs/server-end/framework/egg/tutorial/控制器.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,20 @@ const Controller = require('egg').Controller

class PostController extends Controller {
async create() {
const {ctx, service} = this
const { ctx, service } = this
const createRule = {
title: {type: 'string'},
content: {type: 'string'},
title: { type: 'string' },
content: { type: 'string' },
}
// 校验参数
ctx.validate(createRule)
// 组装参数
const author = ctx.session.userId
const req = Object.assign(ctx.request.body, {author})
const req = Object.assign(ctx.request.body, { author })
// 调用 Service 进行业务处理
const res = await service.post.create(req)
// 设置响应内容和响应状态码
ctx.body = {id: res.id}
ctx.body = { id: res.id }
ctx.status = 201
}
}
Expand All @@ -65,7 +65,7 @@ module.exports = PostController
```js
// app/router.js
module.exports = (app) => {
const {router, controller} = app
const { router, controller } = app
router.post('createPost', '/api/posts', controller.post.create)
}
```
Expand Down Expand Up @@ -99,7 +99,7 @@ Controller 基类的方式封装应用中常用的方法。

```js
// app/core/base_controller.js
const {Controller} = require('egg')
const { Controller } = require('egg')

class BaseController extends Controller {
get user() {
Expand Down Expand Up @@ -144,18 +144,18 @@ class PostController extends Controller {
// app/controller/post.js
exports.create = async (ctx) => {
const createRule = {
title: {type: 'string'},
content: {type: 'string'},
title: { type: 'string' },
content: { type: 'string' },
}
// 校验参数
ctx.validate(createRule)
// 组装参数
const author = ctx.session.userId
const req = Object.assign(ctx.request.body, {author})
const req = Object.assign(ctx.request.body, { author })
// 调用 service 进行业务处理
const res = await ctx.service.post.create(req)
// 设置响应内容和响应状态码
ctx.body = {id: res.id}
ctx.body = { id: res.id }
ctx.status = 201
}
```
Expand Down Expand Up @@ -208,8 +208,7 @@ if (key.startsWith('egg')) {

### Queries

有时候系统会设计成让用户传递相同的 `key`,例如 `GET /posts?category=egg&id=1&id=2&id=3`。针对此类情况,\*
\*框架提供了 `ctx.queries` 对象,这个对象也解析了 `Query String`,但是它不会丢弃任何一个重复的数据,而是将他们都放到一个数组中
有时候系统会设计成让用户传递相同的 `key`,例如 `GET /posts?category=egg&id=1&id=2&id=3`。针对此类情况,\* \*框架提供了 `ctx.queries` 对象,这个对象也解析了 `Query String`,但是它不会丢弃任何一个重复的数据,而是将他们都放到一个数组中
\*\*

```js
Expand Down Expand Up @@ -328,10 +327,9 @@ exports.multipart = {
前端上传代码示例:

```html

<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
title: <input name="title"/> file: <input name="file" type="file"/>
<button type="submit">Upload</button>
title: <input name="title" /> file: <input name="file" type="file" />
<button type="submit">Upload</button>
</form>
```

Expand All @@ -344,14 +342,15 @@ const fs = require('mz/fs')

module.exports = class extends Controller {
async upload() {
const {ctx} = this
const { ctx } = this
const file = ctx.request.files[0]
const name = `egg-multipart-test/${path.basename(file.filename)}`
let result
try {
// 处理文件,比如上传到云端
result = await ctx.oss.put(name, file.filepath)
} finally {
}
finally {
// 需要删除临时文件
await fs.unlink(file.filepath)
}
Expand All @@ -366,17 +365,15 @@ module.exports = class extends Controller {
```

上面的是基于最简单的单个文件上传进行的代码示例,借助`ctx.request.files`
数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助`ctx.request.files`数组,\*
\*不过需要多注意一步——数组遍历\*\*
数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助`ctx.request.files`数组,\* \*不过需要多注意一步——数组遍历\*\*

前端多文件上传:

```html

<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
title: <input name="title"/> file1: <input name="file1" type="file"/> file2:
<input name="file2" type="file"/>
<button type="submit">Upload</button>
title: <input name="title" /> file1: <input name="file1" type="file" /> file2:
<input name="file2" type="file" />
<button type="submit">Upload</button>
</form>
```

Expand All @@ -389,7 +386,7 @@ const fs = require('mz/fs')

module.exports = class extends Controller {
async upload() {
const {ctx} = this
const { ctx } = this
console.log(ctx.request.body)
console.log('got %d files', ctx.request.files.length)
// 遍历文件
Expand All @@ -403,7 +400,8 @@ module.exports = class extends Controller {
try {
// 处理文件,比如上传到云端
result = await ctx.oss.put(`egg-multipart-test/${file.filename}`, file.filepath)
} finally {
}
finally {
// 需要删除临时文件
await fs.unlink(file.filepath)
}
Expand All @@ -423,10 +421,9 @@ module.exports = class extends Controller {
前端示例:

```html

<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
title: <input name="title"/> file: <input name="file" type="file"/>
<button type="submit">Upload</button>
title: <input name="title" /> file: <input name="file" type="file" />
<button type="submit">Upload</button>
</form>
```

Expand All @@ -446,7 +443,8 @@ class UploaderController extends Controller {
let result
try {
result = await ctx.oss.put(name, stream)
} catch (err) {
}
catch (err) {
// 必须将上传的文件流消费掉,要不然浏览器响应会卡死
await sendToWormhole(stream)
throw err
Expand Down Expand Up @@ -489,7 +487,8 @@ class UploaderController extends Controller {
console.log(`value: ${part[1]}`)
console.log(`valueTruncated: ${part[2]}`)
console.log(`fieldnameTruncated: ${part[3]}`)
} else {
}
else {
if (!part.filename) {
// 这时是用户没有选择文件就点击了上传(part 是 file stream,但是 part.filename 为空)
// 需要做出处理,例如给出错误提示消息
Expand All @@ -504,7 +503,8 @@ class UploaderController extends Controller {
let result
try {
result = await ctx.oss.put(`egg-multipart-test/${part.filename}`, part)
} catch (err) {
}
catch (err) {
// 必须将上传的文件流消费掉,要不然浏览器响应会卡死
await sendToWormhole(part)
throw err
Expand All @@ -522,29 +522,29 @@ module.exports = UploaderController
**为了保证文件上传的安全,框架限制了支持的的文件格式,框架默认支持白名单**

```js
// images
// images
'.jpg', '.jpeg', // image/jpeg
'.png', // image/png, image/x-png
'.gif', // image/gif
'.bmp', // image/bmp
'.wbmp', // image/vnd.wap.wbmp
'.webp',
'.tif',
'.psd',
'.png', // image/png, image/x-png
'.gif', // image/gif
'.bmp', // image/bmp
'.wbmp', // image/vnd.wap.wbmp
'.webp',
'.tif',
'.psd',
// text
'.svg',
'.js', '.jsx',
'.json',
'.css', '.less',
'.html', '.htm',
'.xml',
'.svg',
'.js', '.jsx',
'.json',
'.css', '.less',
'.html', '.htm',
'.xml',
// tar
'.zip',
'.gz', '.tgz', '.gzip',
'.zip',
'.gz', '.tgz', '.gzip',
// video
'.mp3',
'.mp4',
'.avi'
'.mp3',
'.mp4',
'.avi'
```

用户可以通过在 `config/config.default.js` 中配置**来新增支持的文件扩展名,或者重写整个白名单**
Expand Down Expand Up @@ -600,8 +600,7 @@ module.exports = {

通过这个 `Getter` 获取 `protocol` 时,首先会判断当前连接是否是加密连接,如果是加密连接,返回 `https`

如果处于非加密连接时,优先读通过 `config.protocolHeaders` 中配置的 header 的值来判断是 HTTP 还是 `https`\*
\*如果读取不到,可以在配置中通过 config.protocol 来设置兜底值,默认为 HTTP。\*\*
如果处于非加密连接时,优先读通过 `config.protocolHeaders` 中配置的 header 的值来判断是 HTTP 还是 `https`\* \*如果读取不到,可以在配置中通过 config.protocol 来设置兜底值,默认为 HTTP。\*\*

`config.protocolHeaders` 默认配置为 `x-forwarded-proto`

Expand Down Expand Up @@ -631,7 +630,7 @@ HTTP 请求都是无状态的,但是 `Web` 应用通常都需要知道发起
class CookieController extends Controller {
// 添加cookies
async add() {
const {ctx} = this
const { ctx } = this
let count = ctx.cookies.get('count')
count = count ? Number(count) : 0
ctx.cookies.set('count', ++count)
Expand All @@ -640,7 +639,7 @@ class CookieController extends Controller {

// 删除cookies
async remove() {
const {ctx} = this
const { ctx } = this
const count = ctx.cookies.set('count', null)
ctx.status = 204
}
Expand All @@ -660,7 +659,7 @@ class CookieController extends Controller {
```js
class PostController extends Controller {
async fetchPosts() {
const {ctx} = this
const { ctx } = this
// 获取 Session 上的内容
const userId = ctx.session.userId
const posts = await ctx.service.post.fetch(userId)
Expand Down Expand Up @@ -704,8 +703,8 @@ class PostController extends Controller {
// 校验参数
// 如果不传第二个参数会自动校验 `ctx.request.body`
this.ctx.validate({
title: {type: 'string'},
content: {type: 'string'},
title: { type: 'string' },
content: { type: 'string' },
})
}
}
Expand All @@ -720,9 +719,10 @@ class PostController extends Controller {
const ctx = this.ctx
try {
ctx.validate(createRule)
} catch (err) {
}
catch (err) {
ctx.logger.warn(err.errors)
ctx.body = {success: false}
ctx.body = { success: false }
}
}
};
Expand All @@ -737,7 +737,8 @@ class PostController extends Controller {
app.validator.addRule('json', (rule, value) => {
try {
JSON.parse(value)
} catch (err) {
}
catch (err) {
return 'must be json string'
}
})
Expand All @@ -748,9 +749,9 @@ app.validator.addRule('json', (rule, value) => {
```js
class PostController extends Controller {
async handler() {
const {ctx} = this
const { ctx } = this
// query.test 字段必须是 json 字符串
const rule = {test: 'json'}
const rule = { test: 'json' }
ctx.validate(rule, ctx.query)
}
};
Expand All @@ -767,13 +768,13 @@ class PostController extends Controller {
```js
class PostController extends Controller {
async create() {
const {ctx} = this
const { ctx } = this
const author = ctx.session.userId
// Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
const req = Object.assign(ctx.request.body, {author})
const req = Object.assign(ctx.request.body, { author })
// 调用 service 进行业务处理
const res = await ctx.service.post.create(req)
ctx.body = {id: res.id}
ctx.body = { id: res.id }
ctx.status = 201
}
}
Expand Down Expand Up @@ -811,7 +812,7 @@ class PostController extends Controller {
```js
class ViewController extends Controller {
async show() {
const {ctx} = this
const { ctx } = this
ctx.body = {
name: 'egg',
category: 'framework',
Expand All @@ -832,7 +833,7 @@ body 设置成一个 Stream,并会同时处理好这个 Stream 上的错误事
```js
class ProxyController extends Controller {
async proxy() {
const {ctx} = this
const { ctx } = this
const result = await ctx.curl(url, {
streaming: true,
})
Expand All @@ -852,7 +853,7 @@ class ProxyController extends Controller {
class HomeController extends Controller {
async index() {
const ctx = this.ctx
await ctx.render('home.tpl', {name: 'egg'})
await ctx.render('home.tpl', { name: 'egg' })
// ctx.body = await ctx.renderString('hi, {{ name }}', { name: 'egg' });
}
};
Expand Down Expand Up @@ -916,9 +917,9 @@ exports.jsonp = {
```js
// app/router.js
module.exports = (app) => {
const {router, controller, jsonp} = app
router.get('/api/posts/:id', jsonp({callback: 'callback'}), controller.posts.show)
router.get('/api/posts', jsonp({callback: 'cb'}), controller.posts.list)
const { router, controller, jsonp } = app
router.get('/api/posts/:id', jsonp({ callback: 'callback' }), controller.posts.show)
router.get('/api/posts', jsonp({ callback: 'cb' }), controller.posts.list)
}
```

Expand Down
Loading

0 comments on commit c92a53c

Please sign in to comment.