diff --git "a/docs/server-end/framework/egg/tutorial/\346\216\247\345\210\266\345\231\250.md" "b/docs/server-end/framework/egg/tutorial/\346\216\247\345\210\266\345\231\250.md" index 11d2c35d1..643f448a7 100644 --- "a/docs/server-end/framework/egg/tutorial/\346\216\247\345\210\266\345\231\250.md" +++ "b/docs/server-end/framework/egg/tutorial/\346\216\247\345\210\266\345\231\250.md" @@ -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 } } @@ -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) } ``` @@ -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() { @@ -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 } ``` @@ -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 @@ -328,10 +327,9 @@ exports.multipart = { 前端上传代码示例: ```html -
- title: file: - + title: file: +
``` @@ -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) } @@ -366,17 +365,15 @@ module.exports = class extends Controller { ``` 上面的是基于最简单的单个文件上传进行的代码示例,借助`ctx.request.files` -数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助`ctx.request.files`数组,\* -\*不过需要多注意一步——数组遍历\*\* +数组,取0号元素完成的。而在实际的应用中,多个文件的上传的场景是非常常见的,此时也是需要借助`ctx.request.files`数组,\* \*不过需要多注意一步——数组遍历\*\* 前端多文件上传: ```html -
- title: file1: file2: - - + title: file1: file2: + +
``` @@ -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) // 遍历文件 @@ -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) } @@ -423,10 +421,9 @@ module.exports = class extends Controller { 前端示例: ```html -
- title: file: - + title: file: +
``` @@ -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 @@ -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 为空) // 需要做出处理,例如给出错误提示消息 @@ -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 @@ -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` 中配置**来新增支持的文件扩展名,或者重写整个白名单** @@ -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`。 @@ -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) @@ -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 } @@ -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) @@ -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' }, }) } } @@ -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 } } } }; @@ -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' } }) @@ -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) } }; @@ -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 } } @@ -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', @@ -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, }) @@ -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' }); } }; @@ -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) } ``` diff --git a/scripts/.exec b/scripts/.exec deleted file mode 100755 index 0d33d7cdb..000000000 --- a/scripts/.exec +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env node -/** - * 脚本执行器,执行shell命令 - */ -const {join} = require('path') -const cwd = join(__dirname, '..') -process.env.PATH = `${join(cwd, 'node_modules', '.bin')}:${process.env.PATH}` -const {exec, exit} = require('shelljs'); - -/** - * 监听进程 - * - 退出进程 - */ -process.on('exit', () => { - exit() -}) - -/** - * 执行shell指令 - */ -exports.execShell = async commands => { - let runCommands = [] - if (typeof commands === 'string') { - runCommands.push(commands) - } - - // 批量执行 - if (Array.isArray(commands)) { - runCommands = commands - } - - // 执行多条 - for (let index = 0; index < runCommands.length; index++) { - const command = runCommands[index] - const count = index + 1 - console.log(`step${count}:\n${command} \nstep${count}(start): === `) - // await syncExec(command) - const execResult = await exec(command) - // 打印输出结果 - console.log(`step${count}(ending): === \n`) - // 指令异常,不执行后续指令,非0退出 - if (execResult.code !== 0) { - exit(1) - break; - } - } -} diff --git a/scripts/bundle b/scripts/bundle index f5cd62cc3..e4e194c39 100755 --- a/scripts/bundle +++ b/scripts/bundle @@ -9,47 +9,26 @@ * - ./scripts/bundle 交互式选择执行的命令 */ -const { execShell } = require('./.exec') -const { execSync } = require('child_process'); -const { Select } = require('enquirer') +import {execShell, promptList, getLogInfo} from '@142vip/utils' +import {name, version} from '../package.json' + +const packageVersion = version +const projectName = name // 仓库地址 const repoAddress = 'registry.cn-hangzhou.aliyuncs.com/142vip/docs' -const packageInfo=require('../package.json') -const packageVersion = packageInfo.version -const projectName = packageInfo.name - // 镜像地址 const imageName = `${repoAddress}:${projectName}-${packageVersion}` -/** - * 获取最近一次Git提交信息 - * - 短哈希值 - * - 提交信息 - */ -async function getGitInfo(){ - // 执行 git log 命令获取最新一次提交的哈希值和消息 - const gitLog = execSync('git log --no-merges -1 --pretty=format:"%h %s"').toString(); - - // 分割输出字符串以获取哈希值和消息 - const [commitHash, ...commitMessage] = gitLog.trim().split(' '); - - // 输出最近一次提交的信息 - return { - gitHash: commitHash, - gitMessage: commitMessage.join(' ') - } -} - /** * 获取构建镜像的脚本 * @param containerBuild 是否容器内构建 * @param preBuild 是否预编译 * @param needProxy 是否配置代理路径 */ -async function getBuildImageScript({ containerBuild, preBuild, needProxy = false }) { +async function getBuildImageScript({containerBuild, preBuild, needProxy = false}) { // 基础构建脚本 let baseBuildScript = '' @@ -57,11 +36,11 @@ async function getBuildImageScript({ containerBuild, preBuild, needProxy = false baseBuildScript = needProxy ? './scripts/bundle build_proxy' : './scripts/bundle build' } - const {gitHash,gitMessage}=await getGitInfo() + const {gitHash, gitMessage} = await getLogInfo() return [ - // 构建镜像 - ` + // 构建镜像 + ` ${baseBuildScript} docker build \ --build-arg CONTAINER_BUILD=${containerBuild} \ @@ -75,8 +54,8 @@ async function getBuildImageScript({ containerBuild, preBuild, needProxy = false --build-arg GIT_MESSAGE="${gitMessage}" \ -t ${imageName} . `, - // 推送镜像 - ` + // 推送镜像 + ` if [ "$(docker images -q ${imageName} 2> /dev/null)" != "" ];then ## 推送 docker push ${imageName} @@ -113,44 +92,40 @@ async function getScriptCommand() { let scriptCommand = SupportScripts.build if (scriptName == null) { - const prompt = new Select({ - header: '======================== JavaScriptCollection Cli For Building ========================', - footer: '======================== JavaScriptCollection Cli For Building ========================', - name: 'color', - message: 'What script will you want to run ', - choices: [ - { - message: 'build to docker image', - name: SupportScripts.image, - value: '#0000ff' - }, - { - message: 'build to docker image with proxy', - name: SupportScripts.image_proxy, - value: '#0000ff' - }, - { - message: 'build to docker image faster', - name: SupportScripts.image_faster, - value: '#0000ff' - } - ] - }) + const prompt = await promptList([ + { + message: 'build to docker image', + name: SupportScripts.image, + value: '#0000ff' + }, + { + message: 'build to docker image with proxy', + name: SupportScripts.image_proxy, + value: '#0000ff' + }, + { + message: 'build to docker image faster', + name: SupportScripts.image_faster, + value: '#0000ff' + } + ], 'What script will you want to run ') scriptCommand = await prompt.run() } else { // 命中支持的脚本 - if (Object.keys(SupportScripts).includes(scriptName)) { scriptCommand = SupportScripts[scriptName] } + if (Object.keys(SupportScripts).includes(scriptName)) { + scriptCommand = SupportScripts[scriptName] + } } return scriptCommand } -;(async() => { - try{ +;(async () => { + try { const scriptCommand = await getScriptCommand() await execShell(scriptCommand) - }catch (e) { - console.log('异常信息:',e) + } catch (e) { + console.log('异常信息:', e) } })()