日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

egg --- 初始化一个egg项目基本结构说明

發(fā)布時間:2023/12/10 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 egg --- 初始化一个egg项目基本结构说明 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Egg.js體驗

  • 全局安裝
// 創(chuàng)建項目 $ npm i egg-init -g $ egg-init egg-example --type=simple $ cd egg-example $ npm i// 啟動項目 $ npm run dev $ open localhost:7000




Egg.js的結(jié)構(gòu)

  • 路由(Router): 將請求URL和具體承擔執(zhí)行動作的Controller的關(guān)系對應(yīng)
  • 控制器(Controller):
    • Restful: 接收用戶的參數(shù),從數(shù)據(jù)中查找內(nèi)容返回給用戶
    • 頁面請求: 根據(jù)用戶訪問不同的URL,渲染不同的模板得到HTML返回給用戶
    • 代理服務(wù)器: 將用戶的請求轉(zhuǎn)發(fā)到其他服務(wù)器上.
  • 服務(wù)(Service):
    • Service就是將復雜業(yè)務(wù)場景下用于做業(yè)務(wù)封裝的一個抽象層
    • 好處:
      • 保持Controller簡潔
      • 業(yè)務(wù)邏輯獨立性: 用戶業(yè)務(wù)PCController + MobileController
      • 邏輯和展現(xiàn)分離:
        • 容易編寫測試用例
        • 無容器依賴對象 (body header)
  • 數(shù)據(jù)庫:
    • mongoose
    • sequelize

基本使用

  • 使用egg-init生成的結(jié)構(gòu)如下
  • 自己添加一個Service層
  • 打開egg-example/app/router.js, 有如下代碼:
module.exports = app => {const { router, controller } = app;router.get('/', controller.home.index); }
  • 在這一層,將路由請求/ 和處理函數(shù) controller.home.index對應(yīng)起來
  • controller.home.index其實是對應(yīng)Controller層.
  • 找到Controller(文件夾)下面的文件home.js,打開如下:
  • 說明:
  • 使用 const Controller = require('egg').Controller得到egg框架中的Controller基類
  • 自定義類繼承與Controller基類 class HomeController extends Controller
  • 在里面聲明了一個異步方法 async index(){...}
  • 將自定義的類導出,module.exports = HomeController
  • 這里的index 對應(yīng)路由層(Router)中的 controller.home.index

類似的加一個Service層

  • 假設(shè)是User的服務(wù)處
  • 首先獲得Service的基類 const Service = require('egg').Service
  • 自定義子類繼承基類const UserService extends Service{...}
  • 在里面寫一個方法,用于獲取所有用戶
  • async getAll(){return [{name:'marron',age:18}] }
  • 導出自己定義的類
    • 目錄結(jié)構(gòu)自己新建,代碼保存于’/egg-example/app/service/user.js’
    const Service = require('egg').Service;class UserService extends Service{async getAll() {return [{ name:'marron', age: 18 }]} }

    在Controller層中使用Service層的服務(wù)

    • 1.首先從this中獲取上下文 const {ctx} = this
    • 2.Service層中(繼承基類Service)的方法全部掛載在ctx.service上
    • 調(diào)用如下:
    'use strict';const Controller = require('egg').Controller;class HomeController extends Controller {async index() {const { ctx } = this;ctx.body = await ctx.service.user.getAll()} }module.exports = HomeController;

    總結(jié)

    以上是生活随笔為你收集整理的egg --- 初始化一个egg项目基本结构说明的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。