08課最佳實戰8月26號論壇_第1頁
08課最佳實戰8月26號論壇_第2頁
08課最佳實戰8月26號論壇_第3頁
08課最佳實戰8月26號論壇_第4頁
免費預覽已結束,剩余8頁可下載查看

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、egg-實戰1. 創建項目# 創建項目npm i egg-init -gegg-init egg-server -type=simple cd egg-servernpm i# 啟動項目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 創建用戶* description 創建用戶, 用戶賬戶/ /類型* router post /api/user* request body createUserRequest *body* response 200 baseResponse 創建*/async create() const ctx = thisctx.body = 'user ctrl'module.exports = UserControllercontract開課吧web全棧架構師/ 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: '手機號' ,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全棧架構師/ 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 上觸發一個 error 事件,框架會記錄一條錯誤日志app.emit('error', err, this)const status = err.status | 500/ 生產環境時 500

8、錯誤的詳細錯誤內容不返回給客戶端,因為可能包含敏感信息const error = status = 500 && app.config.env = 'prod' ? 'Internal Server Error' :err.message/ 從 error 對象上讀出各個屬性,設置到響應中ctx.body = code: status, / 服務端自身的處理邏輯錯誤(包含框架錯誤500 及 自定義業務邏輯錯誤533開始 ) 客戶端請求參數導致的錯誤(4xx開始),設置不同的狀態碼error: errorif (status = 422) ctx.

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

10、Helper 這樣一個簡單的函數,可以讓我們更容易編寫測試用例。框架內置了一些常用的 Helper 函數。我們也可以編寫自定義的 Helper 函數。/ controller/user.js const res = abc:123/ 設置響應內容和響應狀態碼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;)/ 處理成功響應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/ 校驗參數ctx.validate(ctx.rule

12、.createUserRequest)開課吧web全棧架構師添加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全棧架構師bcrypt : enable: true,package: 'egg-bcrypt'/ service/user.jsconst Service = require('egg').Servicecl

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

16、equest body createUserRequest *body* response 200 baseResponse 創建*/async create() const ctx, service = this/ 校驗參數ctx.validate(ctx.rule.createUserRequest)/ 組裝參數const payload = ctx.request.body | / 調用 Service 進行業務處理const res = await service.user.create(payload)/ 設置響應內容和響應狀態碼ctx.helper.success(ctx, res

17、)開課吧web全棧架構師通過生命周期初始化數據/ /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全棧架構師用戶鑒權模塊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全棧架構師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全棧架構師Controller層/ controller/userAccess.js 'use strict'const Controller = require('egg').Controller/* Controller 用戶鑒權*/class UserAccessController extends Controller constructor(ctx

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

27、rvice.userAccess.login(payload)/ 設置響應內容和響應狀態碼ctx.helper.success( ctx, res )/* summary 用戶登出* description 用戶登出* router post /auth/jwt/logout* request body loginRequest *body* response 200 baseResponse 創建*/async logout() const ctx, service = this/ 調用 Service 進行業務處理await service.userAccess.logout()/ 設置響

28、應內容和響應狀態碼ctx.helper.success( ctx )module.exports = UserAccessController開課吧web全棧架構師文件上傳npm i await-stream-ready stream-wormhole image-downloader -scontroller開課吧web全棧架構師/ 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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論