启动
"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()
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
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
};
}