08課最佳實(shí)戰(zhàn)8月26號論壇_第1頁
08課最佳實(shí)戰(zhàn)8月26號論壇_第2頁
08課最佳實(shí)戰(zhàn)8月26號論壇_第3頁
08課最佳實(shí)戰(zhàn)8月26號論壇_第4頁
免費(fèi)預(yù)覽已結(jié)束,剩余8頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、egg-實(shí)戰(zhàn)1. 創(chuàng)建項(xiàng)目# 創(chuàng)建項(xiàng)目npm i egg-init -gegg-init egg-server -type=simple cd egg-servernpm i# 啟動項(xiàng)目npm run devopen localhost:70012.添加swagger-doc- 添加Controller方法/ app/controller/user.jsconst Controller = require('egg').Controller/* Controller 用戶管理*/class UserController extends Controller constructo

2、r(ctx) super(ctx)/* summary 創(chuàng)建用戶* description 創(chuàng)建用戶, 用戶賬戶/ /類型* router post /api/user* request body createUserRequest *body* response 200 baseResponse 創(chuàng)建*/async create() const ctx = thisctx.body = 'user ctrl'module.exports = UserControllercontract開課吧web全棧架構(gòu)師/ app/contract/index.js module.expo

3、rts = baseRequest:id: type: 'string', description: 'id 唯一鍵' ,required:true,example:'1',baseResponse: code: type: 'integer', required: true, example: 0 , data:type: 'string',example: '請求成功' , errorMessage: type: 'string', example: '請求成功'

4、 ,;/ /app/contract/user.js module.exports = createUserRequest: mobile: type: 'string', required: true, description: '手機(jī)號' ,example: ' ', format: /134578d9$/,password: type: 'string', required: true, description: '密碼' ,example: '111111', ,realName: type

5、: 'string', required: true, description: '姓名' ,example:'Tom',添加SwaggerDoc功能 npm install egg-swagger-doc-feat -s/ config/plugin swaggerdoc : enable: true,package: 'egg-swagger-doc-feat',開課吧web全棧架構(gòu)師/ config.default.js config.swaggerdoc = dirScanner: './app/controlle

6、r',apiInfo: title: '開課吧接口',description: '開課吧接口 swagger-ui for egg',version: '1.0.0',schemes: 'http', 'https', consumes: 'application/json', produces: 'application/json', enableSecurity: false,http:/localhost:7001/swagger-ui.html http:/local

7、host:7001/swagger-doc增加異常處理中間件/ /middleware/error_handler.js 'use strict'module.exports = (option, app) => return async function (ctx, next) try await next() catch (err) / 所有的異常都在 app 上觸發(fā)一個 error 事件,框架會記錄一條錯誤日志app.emit('error', err, this)const status = err.status | 500/ 生產(chǎn)環(huán)境時 500

8、錯誤的詳細(xì)錯誤內(nèi)容不返回給客戶端,因?yàn)榭赡馨舾行畔onst error = status = 500 && app.config.env = 'prod' ? 'Internal Server Error' :err.message/ 從 error 對象上讀出各個屬性,設(shè)置到響應(yīng)中ctx.body = code: status, / 服務(wù)端自身的處理邏輯錯誤(包含框架錯誤500 及 自定義業(yè)務(wù)邏輯錯誤533開始 ) 客戶端請求參數(shù)導(dǎo)致的錯誤(4xx開始),設(shè)置不同的狀態(tài)碼error: errorif (status = 422) ctx.

9、body.detail = err.errorsctx.status = 200/ config.default.js config.middleware = 'errorHandler'helper方法實(shí)現(xiàn)統(tǒng)一響應(yīng)格式Helper 函數(shù)用來提供一些實(shí)用的 utility 函數(shù)。開課吧web全棧架構(gòu)師/ enableValidate: true, routerMap: true,enable: true,它的作用在于我們可以將一些常用的動作抽離在 helper.js 里面成為一個獨(dú)立的函數(shù),這樣可以用 JavaScript 來寫復(fù)雜的邏輯,避免邏輯分散各處。另外還有一個好處是

10、Helper 這樣一個簡單的函數(shù),可以讓我們更容易編寫測試用例??蚣軆?nèi)置了一些常用的 Helper 函數(shù)。我們也可以編寫自定義的 Helper 函數(shù)。/ controller/user.js const res = abc:123/ 設(shè)置響應(yīng)內(nèi)容和響應(yīng)狀態(tài)碼ctx.helper.success(ctx, res)/ extend/helper.jsconst moment = require('moment')/ 格式化時間exports.formatTime = time => moment(time).format('YYYY-MM-DD HH:mm:ss&#

11、39;)/ 處理成功響應(yīng)exports.success = ( ctx, res = null, msg = '請求成功' )=> ctx.body = code: 0, data: res, msgctx.status = 200Validate檢查 npm i egg-validate -s/ config/plugin.js validate: enable: true,package: 'egg-validate',async create() const ctx, service = this/ 校驗(yàn)參數(shù)ctx.validate(ctx.rule

12、.createUserRequest)開課吧web全棧架構(gòu)師添加M 層 npm install egg-mongoose -s/ plugin.jsmongoose : enable: true,package: 'egg-mongoose',/ config.default.js config.mongoose = url: 'mongodb:/:27017/egg_x', options: / useMongoClient: true, autoReconnect: true, reconnectTries: Number.MAX_VALU

13、E, bufferMaxEntries: 0,/ m /user.js module.exports = app => const mongoose = app.mongooseconst UserSchema = new mongoose.Schema(mobile: type: String, unique: true, required: true , password: type: String, required: true ,realName: type: String, required: true , avatar: type: String, default:'

14、extra: type: mongoose.Schema.Types.Mixed , createdAt: type: Date, default: Date.now )return mongoose.m ('User', UserSchema)',添加Service層 npm install egg-bcrypt -s開課吧web全棧架構(gòu)師bcrypt : enable: true,package: 'egg-bcrypt'/ service/user.jsconst Service = require('egg').Servicecl

15、ass UserService extends Service /* 創(chuàng)建用戶* param * payload*/async create(payload) const ctx = thispayload.password = await this.ctx.genHash(payload.password) return ctx.m .User.create(payload)module.exports = UserServiceController調(diào)用/* summary 創(chuàng)建用戶* description 創(chuàng)建用戶, 用戶賬戶/ /類型* router post /api/user* r

16、equest body createUserRequest *body* response 200 baseResponse 創(chuàng)建*/async create() const ctx, service = this/ 校驗(yàn)參數(shù)ctx.validate(ctx.rule.createUserRequest)/ 組裝參數(shù)const payload = ctx.request.body | / 調(diào)用 Service 進(jìn)行業(yè)務(wù)處理const res = await service.user.create(payload)/ 設(shè)置響應(yīng)內(nèi)容和響應(yīng)狀態(tài)碼ctx.helper.success(ctx, res

17、)開課吧web全棧架構(gòu)師通過生命周期初始化數(shù)據(jù)/ /app.js/* 全局定義* param app*/class AppBootHook constructor(app) this.app = app; app.root_path = dirname;configWillLoad() / Ready to call configDidLoad,/ Config, plugin files are referred,/ this is the last chance to modify the config.configDidLoad() / Config, plugin files have

18、 been loaded.async didLoad() / All files have loaded, start plugin here.async willReady() / All plugins have started, can do some thing before app readyasync didReady() / Worker is ready, can do some things/ don't need to block the app boot. console.log('=Init Data=')const ctx = await th

19、is.app.createAnonymousContext(); await ctx.m .User.remove();await ctx.service.user.create( mobile: ' ',password: '111111',realName: '老夏',)async serverDidReady() async beforeClose() / Do some thing before app close.開課吧web全棧架構(gòu)師用戶鑒權(quán)模塊jwt模塊 npm i egg-jwt -s/ plugin.js jwt: enable

20、: true, package: 'egg-jwt',/ config.default.js config.jwt = secret: 'Great4-M',enable: true, / default is false match: /api/, / optionalService層/ service/actionToken.js 'use strict'const Service = require('egg').Serviceclass ActionTokenService extends Service async ap

21、ply(_id) const ctx = this return ctx.app.jwt.sign(data: _id: _id,exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7), ctx.app.config.jwt.secret)module.exports = ActionTokenService開課吧web全棧架構(gòu)師module.exports = AppBootHook;/ service/userAccess.js 'use strict'const Service = require('egg&

22、#39;).Service class UserAccessService extends Service async login(payload) const ctx, service = thisconst user = await service.user.findByMobile(payload.mobile) if(!user)ctx.throw(404, 'user not found')let verifyPsw = await pare(payload.password, user.password) if(!verifyPsw) ctx.throw(404,

23、'user password is error')/ 生成Token令牌return token: await service.actionToken.apply(user._id) async logout() async current() const ctx, service = this/ ctx.state.user 可以提取到JWT編碼的data const _id = ctx.state.user.data._idconst user = await service.user.find(_id) if (!user) ctx.throw(404, 'use

24、r is not found')user.password = 'How old are you?' return usermodule.exports = UserAccessServiceContract層/ app/contract/userAccess.js module.exports = loginRequest: mobile: type: 'string', required: true, description: ' 號', example: ' ', format: /134578d9$/, ,pass

25、word: type: 'string', required: true, description: ' ', example: '111111',開課吧web全棧架構(gòu)師Controller層/ controller/userAccess.js 'use strict'const Controller = require('egg').Controller/* Controller 用戶鑒權(quán)*/class UserAccessController extends Controller constructor(ctx

26、) super(ctx)/* summary 用戶登入* description 用戶登入* router post /auth/jwt/login* request body loginRequest *body* response 200 baseResponse 創(chuàng)建*/async login() const ctx, service = this/ 校驗(yàn)參數(shù)ctx.validate(ctx.rule.loginRequest);/ 組裝參數(shù)const payload = ctx.request.body | / 調(diào)用 Service 進(jìn)行業(yè)務(wù)處理const res = await se

27、rvice.userAccess.login(payload)/ 設(shè)置響應(yīng)內(nèi)容和響應(yīng)狀態(tài)碼ctx.helper.success( ctx, res )/* summary 用戶登出* description 用戶登出* router post /auth/jwt/logout* request body loginRequest *body* response 200 baseResponse 創(chuàng)建*/async logout() const ctx, service = this/ 調(diào)用 Service 進(jìn)行業(yè)務(wù)處理await service.userAccess.logout()/ 設(shè)置響

28、應(yīng)內(nèi)容和響應(yīng)狀態(tài)碼ctx.helper.success( ctx )module.exports = UserAccessController開課吧web全棧架構(gòu)師文件上傳npm i await-stream-ready stream-wormhole image-downloader -scontroller開課吧web全棧架構(gòu)師/ app/controller/upload.js const fs = require('fs') const path = require('path')const Controller = require('egg').Controllerconst awaitWriteStream = require('await-stream-ready').write const sendToWormhole = require('stream-wormhole')const download = require('image

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論