Because egg knowledge is rich, divided into two chapters click to see the previous chapter

takeaway

Egg – From Entry to Entry (1)

An egg – mongoose project

10 Ali Monitoring

Node.js Performance Platform (Alinode)

It is a holistic solution for all Node.js applications, providing performance monitoring, security reminders, troubleshooting, performance optimization and other services. It also provides a complete tool chain and services to help developers quickly find and locate online problems.

npm i nodeinstall -g
Copy the code

Egg-alinode is provided for quick access without the need to install additional resident services such as Agenthub.

npm i egg-alinode --save
Copy the code
// /config/plugin.js

exports.alinode = {
    enable:true.package:'egg-alinode',},Copy the code

Apply for a service

Access to console

Console address: node.console.aliyun.com

// config/config.default.js
exports.alinode = {
  enable: true.appid: '* * *'.// The appID generated by the Node.js performance platform for your project
  secret: '* * *'.// Secret generated by the Node.js performance platform for your project
  logdir: '* * *'.// Optional, node. js performance platform log output address absolute path, the same as NODE_LOG_DIR. For example, / TMP/can be omitted
  error_log: [
    // 'Path, array, optional, configurable for exception logs generated by your application at business level ',
    // 'for example: /root/.logs/error.# yyyyy #-#MM#-#DD#.log',
    // 'Do not change the Egg default log output path do not configure this item ',]./ / is optional
  agentidMode:'IP'.// Optional, if set, add some IP information to the instance ID, used for multiple instances with the same hostname (mainly container)
};
Copy the code

Then you can happily monitor your eggs

Get swgger address input browser

There you have it

Say try it out

Enter the value you pass and click Execute

The results of

You can get the value passed by the interface, like Postman, but with better clarity

12.5 Common Problems

This should not be a problem, but if you use egg-static wisely, you will get an error and you will find out

/node_modules/egg-swagger2/app.js

It would be an array, and then an error would have to be a string, and then you know… You make it a string

11 Import static files

11.1 Tested Plug-in Settings

exports.ejs = {
  enable: true.package: 'egg-view-ejs'};Copy the code

11.2 Configuration Settings

A: Static file

config.static = {

      prefix: '/'.dir: path.join(appInfo.baseDir, 'app/public/')}Copy the code

Of course, the problem is, what if you want multiple files

 config.static = {
    prefix: '/'.dir: [ path.join(appInfo.baseDir, 'app/view/'),
      path.join(appInfo.baseDir, 'app/public/uploads/'),
      path.join(appInfo.baseDir, 'app/public/swagger/')]};Copy the code

B: Template Settings

config.view = {
  defaultExt: '.html'.mapping: {
    '.ejs': 'ejs'.'.html': 'ejs',}}Copy the code

11.3 Route Controller Settings

// Put index.html in app/view, static file in public

const { ctx } = this;

// render user.html

yield ctx.render('index');
Copy the code

12 egg-swagger2

12.1 Operation Scenarios

As a backend, for example, someone needs a backend to provide documentation…. Swagger, swagger, swagger, swagger, swagger, swagger, swagger

12.2 installation

npm i egg-swagger2 -S

12.3 Enabling plug-ins

// config/plugin.js
exports.swagger2 = {
  enable: true.package: 'egg-swagger2'};Copy the code

12.4 Plug-in Configuration

In the config. Default. Js configuration

Config. Swagger2 = {enable: true, // Disable swagger base: {/* default config,support cover schemes: [' HTTP ',], host: '127.0.0.1:7001', basePath: '/', Consumes: ['application/json',], Produces: ['application/json',], */ info: {description: 'documentation, version: '1.0.0', title:' documentation ', contact: {email: '[email protected]',}, license: {name: 'Apache 2.0', url: 'http://www.apache.org/licenses/LICENSE-2.0.html'}}, tags: [{name: "admin", the description: 'admin desc'}, {name: 'role', description: 'Role desc', }, ], definitions: { // model definitions }, securityDefinitions: { // security definitions } }, };Copy the code

12.4 example

In the /app/router.js file

12.4.1 post request

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',},},},},},},},},}); }Copy the code

12.4.2 get request

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',},},},},},},}); }Copy the code

12.4.3 Use of Swagger

NPM run dev runs

Get swgger address input browser

There you have it

Say try it out

Enter the value you pass and click Execute

The results of

You can get the value passed by the interface, like Postman, but with better clarity

12.5 Common Problems

This should not be a problem, but if you use egg-static wisely, you will get an error and you will find out

/node_modules/egg-swagger2/app.js

It would be an array, and then an error would have to be a string, and then you know… You make it a string

13 Form verification mechanism

npm egg-validate-plus –save

13.1 Enabling plug-ins

// config/plugin.{env}.js

exports.validatePlus = {
  enable: true,
  package: 'egg-validate-plus',
};
Copy the code

13.2 Configuring Plug-ins

// 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: 'Parameter error'}; }}};Copy the code

13.3 Using plug-ins

13.3.1 Passing a String

// app/controller/xx.js
const { query } = this.ctx.request;
Copy the code

Get the verification results.

const validateResult = await this.ctx.validate('user.login', query)
Copy the code

If the verification fails, block subsequent code execution

if(! validateResult)return
Copy the code


13.3.2 Passing the validation rule object directly

// app/controller/xx.js

// Import validation rules directly under the rules file, or you can write your own validation rule object

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

// Data format

// const rule = {

// id: [

// { required: true },

// {type: 'number', message: 'id must be a number}

/ /,

// password: [

// { required: true },

// {type: 'string', message: 'password must be a string}

/ /]

// }



// A parameter passed in from the client

const { query } = this.ctx.request;

// Data format:
// query = {

// username: 123456,

// password: 'abcdefg'

// }

// Get the validation result

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

// If the verification fails, the following code is prevented from executing

if(! validateResult)return
Copy the code

14 connection redis

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

14.1 installation

npm i egg-redis --save
Copy the code

14.2 configuration

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

exports.redis = {

  enable: true.package: 'egg-redis'};Copy the code

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,}}Copy the code

14.3 Usage

14.3.1 service

App /service/redis.js if(this.app.redis) Checks whether redis is enabled

'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;

Copy the code

14.3.2 controller

App/controller/default/index. Js if not set redis cache, the request data, to set the cache

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);
}
Copy the code

15 an egg – mongoose project

Mongodb is so important to node services that we will make a special topic to discuss it

Juejin. Cn/post / 684490…