Egg快速入门,常用插件配置以及实践。

5,280 阅读4分钟

egg简介

阿里出品:egg官网 这里

Egg.js 为企业级框架和应用而生

官方文档写的都已经很详细了,这里就不再班门弄斧了。

本文主要展示一些常用插件的使用方法等

本文还没有更新完毕,最近会再进行更新

安装和初始化

npm i egg-init -g 
egg-init egg-server --type=simple 
cd egg-server
npm i
# 启动项⽬目
npm run dev 
打开 localhost:7001

接口文档swagger-doc

执行 npm i egg-swagger-doc-feat --save

npm 安装 地址

配置

加载插件

// config/plugin.js
module.exports = {
    swaggerdoc: {
    enable: true,
    package: 'egg-swagger-doc-feat',
  },
}

配置插件

//config/config.default.js
config.swaggerdoc = {
    dirScanner: './app/controller', // 扫描对应文件夹
    apiInfo: {
      title: '测试接口', 
      description: '测试接口 swagger-ui for egg',
      version: '1.0.0',
    },
    schemes: [ 'http', 'https' ], // 支持的协议
    consumes: [ 'application/json' ], // 传输
    produces: [ 'application/json' ],
    enableSecurity: false,
    routerMap: true, // 通过文档定义生成router
    enable: true,
  };

使用

app/contract

index.js

'use strict';
module.exports = {
  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: '请求成功' },
  },
};

主要设置一些基本请求类型基本响应类型

user.js

'use strict';
module.exports = {
  createUserRequest: {
    mobile: {
      type: 'string',
      required: true,
      description: '手机号',
      example: '18801731528',
      format: /^1[34578]\d{9}$/,
    },
    password: { type: 'string', required: true, description: '密码', example: '111111' },
    realName: { type: 'string', required: true, description: '姓名', example: 'Tom' },
  },
};

这个文件主要定义一些实例数据,格式和校验等

app/controller

user.js

'use strict';

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

/**
 *  @Controller用户管理
 */
class UserController extends Controller {
  /**
   * @summary 创建用户
   * @description 创建用户,记录用户账户/密码/类型
   * @router post /api/user
   * @request body createUserRequest *body
   * @response 200 baseResponse 创建成功
   */
  async create() {
    const { ctx } = this;
    ctx.body = 'user ctrl';
  }
}
module.exports = UserController;

这个文件最重要的是 注释部分,各个内容作用参考这里

最后

执行 npm run dev

在命令行会出现这个3行

这时候我们只需要打开 http://localhost:7001/swagger-ui.html 就会看到这个画面

上面 绿色的表示接口,点击出现一个

点击try it out会在下方出现一个 蓝色按钮,点击就会进行测试特别方便。

异常处理

当我们在程序中访问一些不存在的函数或者其他等错误操作,会报错,所以为了解决这个问题,我们需要 定义一个中间件来处理错误

创建

app/middleware

error_handle.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;
      const error = status === 500 && app.config.env === 'prod' ? 'Internal Server Error' : err.message;
      // 从 error 对象上读出各个属性,设置到响应中
      ctx.body = {
        code: status,
        // 服务端自身的处理逻辑错误(包含框架错误500 及 自定义业务逻辑 错误533开始 )
        // 客户端请求参数导致的错误(4xx开始),设置不同的状态码
        error,
      };
      ctx.status = 200;
    }
  };
};

配置

app/config

config.default.js

// 找到 config.middleware 把我们写的中间件注册进去就行
...
config.middleware = [ 'errorHandler' ];
...

Helper

官方定义 这里

还有这个

创建

app/extend

help.js

'use strict';

const moment = require('moment');
// 格式化时间
exports.formatTime = time => moment(time)
  .format('YYYY-MM-DD HH:mm:ss');
// 处理理成功响应
exports.success = ({ ctx, res = null, msg = '请求成功' }) => {
  ctx.body = { code: 0, data: res, msg };
  ctx.status = 200;
};

使用

app/controller

home.js

直接 ctx.helper.success()使用

'use strict';

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

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const res = { abc: 123 };
    // ctx.body = 'hi, egg';
    ctx.helper.success({ ctx, res });
  }
}
module.exports = HomeController;

结果

直接访问 http://localhost:7001/,也可以使用postman

Validate检查

安装npm i egg-validate -s

npm 地址

配置

// config/plugin.js
module.exports = {
    ...
    swaggerdoc: {
    enable: true,
    package: 'egg-validate',
  },
}

使用

async create() {
    const { ctx } = this;
    // 校验参数
    ctx.validate(ctx.rule.createUserRequest);
  }

结果

不通过就会出现这个

添加数据库操作(添加Model层)

这里选用 mongodb

执行npm install egg-mongoose -s

配置

加载插件

// config/plugin.js
....
mongoose: { enable: true, package: 'egg-mongoose' },

配置插件

npm 地址

//config/config.default.js
config.mongoose = {
    url: 'mongodb://127.0.0.1:27017/egg_x',
    options: {
      // useMongoClient: true
      autoReconnect: true,
      reconnectTries: Number.MAX_VALUE,
      bufferMaxEntries: 0,
    },
  };

定义

app/model

user.js

'use strict';
module.exports = app => {
  const mongoose = app.mongoose;
  const UserSchema = new mongoose.Schema({
    mobile: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    realName: { type: String, required: true },
    extra: { type: mongoose.Schema.Types.Mixed },
    createdAt: { type: Date, default: Date.now },
  });
  return mongoose.model('User', UserSchema);
};

具体操作参考 mongoose地址

使用

app/controller

user.js

'use strict';

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

/**
 *  @Controller用户管理
 */
class UserController extends Controller {
  /**
   * @summary 创建用户
   * @description 创建用户,记录用户账户/密码/类型
   * @router post /api/user
   * @request body createUserRequest *body
   * @response 200 baseResponse 创建成功
   */
  async create() {
    const { ctx } = this;
    // 校验参数
    ctx.validate(ctx.rule.createUserRequest);
    // 组装参数
    const payload = ctx.request.body || {};
    const res = await ctx.model.User.create(payload);
    // 设置响应内容和响应状态码
    ctx.helper.success({ ctx, res });
  }
}
module.exports = UserController;

结果

数据库里面会存在一条数据

添加Service层

安装npm install egg-bcrypt -s

声明:,这个与service层无关,是用来加密密码的

配置插件

//config/config.default.js
bcrypt : {    enable: true,  package: 'egg-bcrypt'  }

创建service

app/service

user.js

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

class UserService extends Service {
  /**
   * 创建⽤用户
   * @param {*} payload
   */
  async create(payload) {
    const { ctx } = this;
    payload.password = await this.ctx.genHash(payload.password);
    return ctx.model.User.create(payload);
      // 创建用户
  }
}

module.exports = UserService;

使用

'use strict';

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

/**
 *  @Controller用户管理
 */
class UserController extends Controller {
  /**
   * @summary 创建用户
   * @description 创建用户,记录用户账户/密码/类型
   * @router post /api/user
   * @request 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 });
  }
}
module.exports = UserController;

结果。

数据库多了一条信息