1. The integrated swagger

npm install egg-swagger-doc-feat -s


// Note that this is automatically resolved in app/contract
// Define the folder app/contract/index.js object format
module.exports = {
    baseRequest: {
        id: {
            type: 'string'.description: 'id unique key '.required: true.example: '1'}},baseResponse: {
        code: {
            type: 'integer'.required: true.example: 0
        },
        data: {
            type: 'string'.example: 'Request successful'
        },
        errorMessage: {
            type: 'string'.example: 'Request successful',}}};// Define the app/contract/user.js object format
module.exports = {
    createUserRequest: {
        mobile: {
            type: 'string'.required: true.description: 'Mobile phone Number'.example: '18801731528'.format: /^1[34578]\d{9}$/,},password: {
            type: 'string'.required: true.description: 'password'.example: '111111',},realName: {
            type: 'string'.required: true.description: 'name'.example: 'Tom'}},}//config/plugin.js
// Add a plug-in
module.exports = {
  swaggerdoc: {
    enable: true.package: 'egg-swagger-doc-feat',}};// config.default.js
// Define the interface format
  config.swaggerdoc = {
    dirScanner: './app/controller'.apiInfo: {
      title: 'interface'.description: 'Interface swagger- UI for egg'.version: '1.0.0',},schemes: ['http'.'https'].consumes: ['application/json'].produces: ['application/json'].enableSecurity: false.routerMap: true.enable: true,}// Define the document class
//app/controller/user.js
const Controller = require('egg').Controller
/ * * *@Controller User management */
class UserController extends Controller {
    constructor(ctx) {
        super(ctx)
    }
    / * * *@summary Create a user@description: Creates a user and records user information *@router post /api/user
     * @request body createUserRequest *body
     * @reponse 200 baseResponse created successfully */
    async create() {
        const {ctx} = this
        // ap11p()
        // ctx.body = 'user ctrl'
        // ctx.body = this.success()
        const res = {aa:'ddd'}
        ctx.helper.success({ctx, res})
    }

}
module.exports = UserController
  
  
  / / test address: http://localhost:7001/swagger-ui.html
Copy the code

2. Unified exception handling

// Note that this is resolved automatically in the app/ Middleware folder
// /middleware/error_handler.js
'use strict'
module.exports = (option, app) = > {
  return async function (ctx, next) {
    try {
      await next()
    } catch (err) {
      // All exceptions raise an error event on the app, and the framework logs an error
      app.emit('error', err, this)
      const status = err.status || 500
      // The details of the 500 error in production are not returned to the client because they may contain sensitive information
      const error = status === 500 && app.config.env === 'prod' ?
        'Internal Server Error' :
        err.message
      // Read each property from the error object and set it into the response
      ctx.body = {
        code: status, // Server's own processing logic error (including frame error 500 and custom business logic error 533 start) client request parameter error (4xx start), set different status code
        error: error
      }
      if (status === 422) {
        // ctx.body.detail = err.errors
      }
      ctx.status = 200}}}// Register middleware
//config/config.default.js
config.middleware = ['errorHandle']; // Note that error_handler.js is changed to a hump name

// An error is intentionally reported in the corresponding Controller
const Controller = require('egg').Controller;
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    aa() // Call an undefined method test
    ctx.body = 'hi, egg'; }}module.exports = HomeController;

Copy the code

3. General tools

// Note that this is resolved automatically in the app/extend folder
//app/extend/helper.js 

const moment = require('moment')// Use the date tool
// The response was processed successfully
exports.success = ({ ctx, res = null, msg = 'Processing successful' }) = > {
    ctx.body = {
        code: 0.data: res,
        msg
    }
    ctx.status = 200
}
// Format the time
exports.formatTime = time= > moment(time).format('YYYY-MM-DD HH:mm:ss')


/ / test
const Controller = require('egg').Controller
class UserController extends Controller {
    constructor(ctx) {
        super(ctx)
    }
    async create() {
        const {ctx} = this
        // ap11p()
        const res = {aa:'ddd'}
        ctx.helper.success({ctx, res})// Invoke the inherited utility class}}module.exports = UserController

Copy the code

4. Add verification

/ / install libraries
npm i egg-validate -s
//config/plugin.js
  validate: {
    enable: true.package: 'egg-validate'
  },
//controller/user.js
async create() { 
const { ctx, service } = this // Check parameters
ctx.validate(ctx.rule.createUserRequest) 
}
Copy the code

5. Add the Model layer

/ / install libraries
npm install egg-mongoose -s
//config/plugin.js
mongoose : { 
enable: true.package: 'egg-mongoose',}// config.default.js 
config.mongoose = { url: 'mongo: / / 127.0.0.1:27017 / XXX'.options: { // useMongoClient: true, 
    autoReconnect: true.reconnectTries: Number.MAX_VALUE, 
    bufferMaxEntries: 0,}}//app/model/user.js
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 },
        avatar: { type: String.default: 'https://1.gravatar.com/avatar/a3e54af3cb6e157e496ae430aed4f4a3?s=96&d=mm' },
        extra: { type: mongoose.Schema.Types.Mixed },
        createdAt: { type: Date.default: Date.now }
    })
    return mongoose.model('User', UserSchema)
} 

Copy the code

6. Add the service

npm install egg-bcrypt -s

//app/service/user.js
const Service = require('egg').Service

class UserService extends Service {
  
  /** * Create user *@param {*} payload 
   */
  async create(payload) {
    const { ctx, service } = this
    payload.password = await this.ctx.genHash(payload.password)
    return ctx.model.User.create(payload)
  }

}
module.exports = UserService


//app/controller/user.js
const Controller = require('egg').Controller
/ * * *@Controller User management */
class UserController extends Controller {
    constructor(ctx) {
        super(ctx)
    }
    / * * *@summary Create a user@description: Creates a user and records user information *@router post /api/user
     * @request body createUserRequest *body
     * @reponse 200 baseResponse created successfully */
    async create() {
        const {ctx} = this
        // ap11p()
        // ctx.body = 'user ctrl'
        // ctx.body = this.success() 
        ctx.validate(ctx.rule.createUserRequest)

        const palyload = ctx.request.body || {}

        const res = await this.service.user.create(palyload)

        // const res = {aa:'ddd'}
        ctx.helper.success({ctx, res})
    }
}
module.exports = UserController
Copy the code