egg-sequelize

325 阅读2分钟

启动

"start": "egg-scripts start --title=egg-server --port=8080",
"dev": "egg-bin dev --port=8080",

config/plugin.js

// 插件配置
sequelize: {
    enable: true,
    path: 'egg-sequelize'
}

config

module.exports = appInfo => {
  
    const config = {}
  
    config.keys = appInfo.name
  
    config.middleware = [];

    config.security = {
      csrf: {
        enable: false,
      }
    }
  
    config.sequelize = {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306,
      database: databaseName, // 库名
      username: 'root',
      password: '',
      timezone: '+08:00',
      define: {
        // 表名不会增加复数
        freezeTableName: true,
        createdAt: false,
        updatedAt: false
      },
    }
    // 日志文件
    config.logger = {
      dir: process.cwd() + '/logs',
    }

    return {
      ...config
    }
  }

app/router.js

module.exports = app => {
    const { router, controller } = app
    // 健康检查(检测服务是否在工作)
    router.get('/health', controller.health.index)
}

Controller

const BaseContextClass = require('egg').BaseContextClass;
const { Success, Error } = require('../utils')

// 标签接口
class DemoController extends BaseContextClass {
    // 增删改查对应的方法
    async create() {
        const { ctx } = this
        const { success, msg } = await ctx.service.demo.create()
        ctx.body = success ? Success(true) : Error(msg)
    }
}

Service(对数据库的操作)

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


class demoService extends BaseContextClass {
  async findAll() {
    const { app } = this

    try {
        const res = await app.model.Demo.findAll()
        // 记得 toJSON 一下
        return (res || []).map(i => i.toJSON())
        
    } catch(e) {
        return e
    }
  }

  async update() {
    const { ctx, app } = this
    const { id, name } = ctx.request.body
    // 事务的使用
    let transaction = await this.ctx.model.transaction();

    try {
        const res = await app.model.Demo.update(
          { name },
          { where: { id }, transaction }
        )
        
        // 如果没有问题就提交事务
        await transaction.commit();
        return res ? { success: true } : { success: false, msg: '编辑失败' }
        
    } catch(e) {
        // 事务回滚
        await transaction.rollback()
        return {
          success: false,
          msg: '数据库出了一点问题'
        }
    }
  }

  async del() {
    const { ctx, app } = this
    const { id } = ctx.request.body
    let transaction = await this.ctx.model.transaction();

    try {
        const res = await app.model.Demo.destroy({ where: { id }, transaction })
        await transaction.commit();
        return res ? { success: true } : { success: false, msg: '删除失败' }
        
    } catch(e) {
        await transaction.rollback()
        return {
          success: false,
          msg: '数据库出了一点问题'
        }
    }
  }

  async create() {
    const { ctx, app } = this
    const { name } = ctx.request.body

    try {
      // 检查名字是否存在
      const exit = await app.model.Demo.findAll({ where: { name } })
      
      if (exit && exit.length){
        return {
          success: false,
          msg: '名称已存在'
        }
      }

      // 创建新的数据
      const res = await app.model.Demo.create({ name })
      return res ? { success: true } : { success: false, msg: '插入失败' }
      
    } catch(e) {
        return {
          success: false,
          msg: '数据库出了一点问题'
        }
    }
  }
};
// 多条数据的操作
await Promise.all(ary.map(async t => {
    const res = await app.model.Demo.create({
        name
    }, { transaction })

    if (!res) throw '插入失败'
}))
await transaction.commit();
// 分页查询
const { count, rows } = await app.model.Demo.findAndCountAll({
    offset: (page - 1) * pageSize,
    limit: pageSize,
    where: {
      name: {
        // 模糊搜索 
        [app.Sequelize.Op.like]: `%${name}%`
      },
      ...filters
    },
    // 按创建时间排序
    order:[
      ['created_at','desc']
    ]
  })

model表

module.exports = app => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
 
     const MetadataTag = app.model.define('metadata_tag', {
         id: { type: INTEGER, primaryKey: true, autoIncrement: true },
         name: STRING(50),
         created_at: DATE,
         updated_at: DATE,
     });
 
    return MetadataTag;
};

app.js

// 从 nacos 服务器上拉取数据库的配置
const { initNacosConfig } = require('./lib/configHandler');

class App {

  constructor(app) {
    this.app = app;
  }

  async configWillLoad() {
    initNacosConfig(this.app);
  }

}

module.exports = App;

utils

function Success(data) {
    return {
        data,
        code: 200,
        message: 'success'
    };
}

function Error(message, code = 500) {
    return {
        data: null,
        code,
        message
    };
}