egg-從入門到上線 (下)

由於egg知識點豐富,分爲上下兩章點擊見上章javascript

juejin.im/post/5c99cb…html

10 阿里監控

Node.js 性能平臺(alinode)java

是面向全部 Node.js 應用提供 性能監控、安全提醒、故障排查、性能優化 等服務的總體性解決方案,提供完善的工具鏈和服務,協助開發者快速發現和定位線上問題。node

npm i nodeinstall -g
複製代碼

提供了egg-alinode  來快速接入,無需安裝 agenthub 等額外的常駐服務。git

npm i egg-alinode --save
複製代碼
// /config/plugin.js

exports.alinode = {
    enable:true,
    package:'egg-alinode',
},
複製代碼

申請一下服務 github

訪問控制檯

控制檯地址:node.console.aliyun.comredis

image.png

image.png

// config/config.default.js
exports.alinode = {
  enable: true,
  appid: '***',  // Node.js 性能平臺給您的項目生成的 appid
  secret: '***',  // Node.js 性能平臺給您的項目生成的 secret
  logdir: '***',  //可選,Node.js 性能平臺日誌輸出地址絕對路徑,與 NODE_LOG_DIR 保持一致。如:/tmp/,也能夠不寫
  error_log: [
    // '您的應用在業務層面產生的異常日誌的路徑,數組,可選,可配置多個',
    // '例如:/root/.logs/error.#YYYY#-#MM#-#DD#.log',
    // '不更改 Egg 默認日誌輸出路徑可不配置本項目',
  ],// 可選
  agentidMode:'IP',  // 可選,若是設置,則在實例ID中添加部分IP信息,用於多個實例 hostname 相同的場景(以容器爲主)
};
複製代碼

而後你就能愉快針對你的egg,進行監控了mongodb

image.png

獲取swgger地址 輸入瀏覽器apache

你看到就是文檔了npm

image.png

點擊try it out

image.png

輸入你傳的值,而後點擊Execute

image.png

結果

image.png

你就能夠獲取到接口傳遞過來的值,效果相似postman,可是清晰程度比postman好

12.5 常見問題

通常狀況下都不會有問題,可是若是你這時候巧妙的用了egg-static,那麼你就會報錯了
通過排查,你就會發現

/node_modules/egg-swagger2/app.js

image.png

它會是一個數組,而後報錯必須是個字符串,而後你懂得..你給他作成一個字符串便可

11 引入靜態文件

11.1 通過測試插件設置

exports.ejs = {
  enable: true,
  package: 'egg-view-ejs',
};
複製代碼

11.2 配置設置

a:靜態文件

config.static = {

      prefix: '/',

      dir: path.join(appInfo.baseDir, 'app/public/')

    }
複製代碼

固然此時你會遇到一個問題,你想要多個文件該如何事好

config.static = {
    prefix: '/',
    dir: [ path.join(appInfo.baseDir, 'app/view/'),
      path.join(appInfo.baseDir, 'app/public/uploads/'),
      path.join(appInfo.baseDir, 'app/public/swagger/') ],
  };
複製代碼

b:模板設置

config.view = {
  defaultExt: '.html',
  mapping: {
    '.ejs': 'ejs',
    '.html': 'ejs',
  }
}
複製代碼

11.3 路由控制器設置

//將 index.html 放在app/view裏,靜態文件放在public裏

const { ctx } = this;

// render user.html

yield ctx.render('index');
複製代碼

12 egg-swagger2

12.1 運營場景

做爲後臺,例若有人須要後臺提供文檔....人家java都有swagger,egg在 egg-swagger2 支持下,咱們也可使用。

12.2 安裝

npm i egg-swagger2 -S

12.3 開啓插件

// config/plugin.js
exports.swagger2 = {
  enable: true,
  package: 'egg-swagger2',
};
複製代碼

12.4 插件配置

config.default.js 中配置

config.swagger2 = {
    enable: true, // 禁用swagger , 默認爲true
    base: {
      /* default config,support cover
      schemes: [
          'http',
      ],
      host: '127.0.0.1:7001',
      basePath: '/',
      consumes: [
      'application/json',
      ],
      produces: [
      'application/json',
      ],
      */
      info: {
        description: '文檔介紹,
        version: '1.0.0',
        title: '文檔名稱',
        contact: {
          email: 'caandoll@aliyun.com',
        },
        license: {
          name: 'Apache 2.0',
          url: 'http://www.apache.org/licenses/LICENSE-2.0.html',
        },
      },
      tags: [{
          name: 'admin',
          description: 'Admin desc',
        },
        {
          name: 'role',
          description: 'Role desc',
        },
      ],
      definitions: {
        // model definitions
      },
      securityDefinitions: {
        // security definitions
      }
    },
  };
複製代碼

12.4 例子

在  /app/router.js文件中

12.4.1 post請求

module.exports = app => {
   const { router, controller, swagger } = app;
   router.post('/login', controller.test.postLogin);
   swagger.post('/login', {
       tags: [
         'admin',
       ],
       summary: 'Login a admin',
       description: '',
       parameters: [
         {
           in: 'body',
           name: 'body',
           description: 'admin\'s username & password',
           required: true,
           schema: {
             type: 'object',
             required: [ 'username', 'password' ],
             properties: {
               username: {
                 type: 'string',
                 description: 'admin\'s username',
               },
               password: {
                 type: 'string',
                 description: 'admin\'s password',
               },
             },
           },
         },
       ],
       responses: {
         200: {
           description: 'SUCCEED',
           schema: {
             type: 'object',
             properties: {
               status: {
                 type: 'string',
                 description: 'status',
               },
               data: {
                 type: 'object',
                 description: 'data',
                 properties: {
                   token: {
                     type: 'string',
                     description: 'token',
                   },
                 },
               },
             },
           },
         },
       },
     });
}
複製代碼

12.4.2 get請求

module.exports = app => {
   const { router, controller, swagger } = app;
   router.get('/roles', controller.test.getRoles);
   swagger.get('/roles', {
     tags: ['role',],
     summary: 'search role by page',
     description: '',
     parameters: [{
       in: 'query',
       name: 'name',
       description: 'role\'s name',
     },
                  {
                    in: 'query',
                    name: 'pageIndex',
                    description: 'pageIndex',
                  },
                  {
                    in: 'query',
                    name: 'pageSize',
                    description: 'pageSize',
                  },
                 ],
     responses: {
       200: {
         description: 'SUCCEED',
         schema: {
           type: 'object',
           properties: {
             status: {
               type: 'string',
               description: 'status',
             },
             datas: {
               type: 'array',
               description: 'result datas',
               properties: {
                 token: {
                   type: 'string',
                   description: 'token',
                 },
               },
             },
             pageIndex: {
               type: 'number',
               description: 'pageIndex',
             },
             pageSize: {
               type: 'number',
               description: 'pageSize',
             },
             totalCount: {
               type: 'number',
               description: 'totalCount',
             },
           },
         },
       },
     },
   });
}
複製代碼

12.4.3 swagger的使用

npm run dev   跑起來

image.png

獲取swgger地址 輸入瀏覽器

你看到就是文檔了

image.png

點擊try it out

image.png

輸入你傳的值,而後點擊Execute

image.png

結果

image.png

你就能夠獲取到接口傳遞過來的值,效果相似postman,可是清晰程度比postman好

12.5 常見問題

通常狀況下都不會有問題,可是若是你這時候巧妙的用了egg-static,那麼你就會報錯了
通過排查,你就會發現

/node_modules/egg-swagger2/app.js

image.png

它會是一個數組,而後報錯必須是個字符串,而後你懂得..你給他作成一個字符串便可

13 表單校驗機制

npm egg-validate-plus --save

13.1 開啓插件

// config/plugin.{env}.js

exports.validatePlus = {
  enable: true,
  package: 'egg-validate-plus',
};
複製代碼

13.2 配置插件

// config/config.{env}.js

config.validatePlus = {

  resolveError(ctx, errors) {

    if (errors.length) {

      ctx.type = 'json';

      ctx.status = 400;

      ctx.body = {
        code: 400,
        error: errors,
        message: '參數錯誤',
      };
    }
  }
};
複製代碼

13.3 使用插件

13.3.1 傳入字符串

// app/controller/xx.js
const { query } = this.ctx.request;
複製代碼

拿到驗證結果

const validateResult = await this.ctx.validate('user.login', query)
複製代碼

驗證不經過時,阻止後面的代碼執行

if (!validateResult) return
複製代碼

> 注意:不要帶上 rules

13.3.2 直接傳入驗證規則對象

// app/controller/xx.js

// 直接引入 rules 文件下的驗證規則,也能夠是本身寫的驗證規則對象

const rule = this.app.rules.user.login

// 數據格式

// const rule = {

// id: [

// { required: true },

// { type: 'number', message: 'id 必須爲數字 }

// ],

// password: [

// { required: true },

// { type: 'string', message: 'password 必須爲字符串 }

// ]

// }



// 從客戶端傳入的參數

const { query } = this.ctx.request;

// 數據格式:
// query = {

// username: 123456,

// password: 'abcdefg'

// }

// 拿到驗證結果

const validateResult = await this.ctx.validate(rule, query)

// 驗證不經過時,阻止後面的代碼執行

if (!validateResult) return
複製代碼

14 鏈接redis

Redis client(support redis portocal) based on ioredis for egg framework

14.1 安裝

npm i egg-redis --save
複製代碼

14.2 配置

Change ${app_root}/config/plugin.js to enable redis plugin:

exports.redis = {

  enable: true,

  package: 'egg-redis',

};
複製代碼

Configure redis information in ${app_root}/config/config.default.js:
Single Client

config.redis = {
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
  }
}
複製代碼

14.3 使用方法

14.3.1 service

app/service/redis.js if(this.app.redis)判斷是否有啓用redis

'use strict';

const Service = require('egg').Service;

class RedisService extends Service {
  async set(key, value, seconds) {
    value = JSON.stringify(value);
    if (this.app.redis) {
      if (!seconds) {
        await this.app.redis.set(key, value);
      } else {
        await this.app.redis.set(key, value, 'EX', seconds);
      }
    }
  }

  async get(key) {
    if (this.app.redis) {
      const data = await this.app.redis.get(key);
      if (!data) return;
      return JSON.parse(data);
    }
  }
}

module.exports = RedisService;

複製代碼

14.3.2 controller

app/controller/default/index.js若是沒有設置redis緩存,就去請求數據,再設置緩存

var topNav = await this.ctx.service.cache.get('index_topNav');
if (!topNav) {
  topNav = await this.ctx.model.Nav.find({
    "position": 1
  });
  await this.ctx.service.cache.set('index_topNav', topNav, 60 * 60);
}
複製代碼

15 egg-mongoose專題

mongodb 對於node服務重要性不言而喻因此特別作一個專題來討論

juejin.im/post/5cf497…

相關文章
相關標籤/搜索