#mysql数据库中创建表
CREATE TABLE `eggs` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(255) DEFAULT NULL ,
`birth` varchar(255) DEFAULT NULL ,
`sign` varchar(255) DEFAULT NULL ,
`created_at` datetime DEFAULT NULL ,
`updated_at` datetime DEFAULT NULL ,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`sign`)
)CHARSET=utf8mb4 ;
安装 相关依赖
npm install egg-sequelize egg-cors --save
//配置
//config/pulgin.js
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
exports.cors = {
enable: true,
package: 'egg-cors',
};
//config/config.default.js
config.sequelize = {
dialect: 'mysql', //使用什么数据库,支持mysql,mssql,mariadb,postgres
dialectOptions: {
//utf8的超集
charset: 'utf8mb4',
},
database: 'eggs',
host: 'localhost',
port: '3306',
password: 'abcdef'
// 中国在东八区晚标准时间8个小时,所以时区+8,避免出现读写时间不一致
timezone: '+08:00',
};
config.security = {
csrf: {
enable: false,
},
// 设置白名单地址,要发送请求到该服务器的地址
// domainWhiteList: []
};
config.cors = {
//允许携带cookie
credentials: true,
};
//建模
// app/model/eggs.js
'use strict';
module.exports = app => {
const {
INTEGER,
STRING,
DATE
} = app.Sequelize;
const Eggs= app.model.define('eggs', {
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
name: STRING,
birth: STRING,
sigh: STRING,
// 后面两个sequelize会自动创建
created_at: DATE,
updated_at: DATE
}, {
freezeTableName: true, //使用默认表名
// freezeTableName禁用修改表名;默认情况下,
// sequelize会自动将模型名称(第一个参数定义)为复数。
// 值为ture时不修改
// tableName 使用的数据库表名,不写则默认是模型名称
// timestamps是否自动添加时间戳createAt,updateAt
})
return Eggs;
}
// 这个 Model 就可以在 Controller
// 和 Service 中通过 app.model.Eggs 或者 ctx.model.Eggs 访问到了,
//app/service/egg.js
'use strict';
const Service = require('egg').Service;
let ERROR = {
code: 1,
msg: 'failed',
};
let SUCCESS = {
code: 0,
msg: 'success',
};
class EggsService extends Service {
async create(eggs){
const { ctx } = this;
try{
// 调用sequelize的create方法,安照定义的模型传入参数创建数据
eggs = await ctx.model.Eggs.create(eggs);
if(!eggs){
ctx.status = 400;
return Object.assign(ERROR, {
msg: `expectd eggs, but got ${JSON.stringify(eggs)}`
});
}
ctx.status = 200;
return Object.assign(SUCCESS, {
data: eggs
});
}catch(e){
ctx.status = 500;
throw(e);
//TODO handle the exception
}
}
async destroy(id){
const { ctx } = this;
try {
// findById已经被findByPk替代
// 调用sequelize的findByPk方法,传入id查询数据
const eggs = await ctx.model.Eggs.findByPk(id);
if(!eggs) {
ctx.status = 400;
return Object.assign(ERROR, {
msg: 'not found eggs'
});
}
// 调用sequelize的destroy方法,将查询出来的数据删除
const res = await eggs.destroy();
ctx.status = 200;
return Object.assign(SUCCESS, {
data: res
})
} catch(e) {
ctx.status = 500;
throw(e);
}
}
async update({
id,
body
}) {
const { ctx } = this;
try{
const eggs = await ctx.model.Eggs.findByPk(id);
if(!eggs) {
ctx.status = 400;
return Object.assign(ERROR, {
msg: 'not found eggs'
})
}
const res = await eggs.update(body);
ctx.status = 200;
return Object.assign(SUCCESS, {
data: res
});
} catch(e) {
ctx.status = 500;
throw(e);
//TODO handle the exception
}
}
async find(id) {
const { ctx } = this;
try{
const eggs = await ctx.model.Eggs.findByPk(id);
if(!eggs){
ctx.status = 400;
return Object.assign(ERROR, {
msg: 'not fount eggs'
})
}
ctx.status = 200;
return Object.assign(SUCCESS, {
data: eggs
})
}catch(e){
ctx.status = 500;
throw(e)
//TODO handle the exception
}
}
async list({
offset = 0,
limit = 10,
order_by = 'created_at',
order = 'DESC'
}) {
const { ctx } = this;
const options = {
offset: parseInt(offset),
limit: parseInt(limit),
order: [
[order_by, order.toUpperCase()]
]
}
try{
const res = await ctx.model.Eggs.findAndCountAll(options);
if(!res){
ctx.status = 400;
return Object.assign(ERROR, {
msg: 'not found eggs'
})
}
ctx.status = 200;
return Object.assign(SUCCESS, {
data: res
})
}catch(e){
ctx.status = 500;
throw(e);
//TODO handle the exception
}
}
}
module.exports = EggsService;
//app/controller/egg.js
'use strict';
const Controller = require('egg').Controller;
class EggsController extends Controller {
async create(){
const { ctx } = this;
const body = ctx.request.body;
console.log(body, 'mynameisbody');
ctx.body = await ctx.service.eggs.create(body);
}
async destroy(){
const { ctx } = this;
const id = +ctx.params.id; //隐式变换
console.log(id);
ctx.body = await ctx.service.eggs.destroy(id);
}
async update(){
const { ctx } = this;
const id = +ctx.params.id;
const body = ctx.request.body;
ctx.body = await ctx.service.eggs.update({
id,
body
})
}
async find(){
const { ctx } = this;
const id = +ctx.params.id;
ctx.body = await ctx.service.eggs.find(id);
}
async list() {
const { ctx } = this;
const query = ctx.query;
ctx.body = await ctx.service.eggs.list(query);
}
}
module.exports = EggsController;
//router.js
router.post('/api/eggs',controller.eggs.create);
router.delete('/api/eggs/:id', controller.eggs.destroy);
router.put('/api/eggs/:id', controller.eggs.update);
router.get('/api/eggs', controller.eggs.list);
router.get('/api/eggs/:id', controller.eggs.find);
然后就可以使用postman进行调试了
链接: egg-sequelize 链接多个数据库.