说明
- 上一篇: MVC实现之四
- 这一篇主要介绍:
- 项目中用到的Sequelize库中的一些方法,参考使用Sequelize连接mysql
- 将Model层加入Mar类中
Service层
- 还是从业务出发,Service层是调用方,调用方式和Controller层调用Service层一样
class Service {
constructor(app) {
const { model } = app;
Service.prototype.model = model;
}
async index() {
const model = Service.prototype.model;
let data = awati model.index();
data.age = 20;
data.remarks = `forever 18`;
return data;
}
}
Mar类
- 设计原则是,在不同层之间传递参数,通过Mar类.
- 故需要在Mar类中挂载Model
- 改写Mar类如下
class Mar {
constructor(conf) {
this.$app = new koa(conf);
this.$router = new koaRouter();
this.model = new Model(this); // 这一行是新加的
this.service = new Service(this);
this.controller = new Controller(this);
this.router = new Router(this);
}
listen(port){ /* 未改变 */}
}
Model类 - 初始化
- 新建Mar类如下
class Mar {
constructor ( app ) {
console.log('Model ok');
}
test() {
return 'Model for Service'
}
async index() {
return {
name: 'marron'
}
}
}
- 此时启动服务器,访问
http://localhost:3000
Model类-操作数据库
- 准备数据库,按照docker-compose.yml构建容器.
- 浏览器打开管理页面
注: 密码是example - 新建数据库
marron
- 准备就绪后,连接数据库,并测试
连接数据库
- Sequelize库提供的接口如下
const sequelize = new Sequelize('marron', 'root', 'example', {
host: 'localhost',
dialect: 'mysql'
})
sequelize
.authenticate()
.then(() => {
console.log('Connect has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
- 写到Model类里面
- 进入Model类的时候,连接到数据库
- 有一个testSQL方法用于测试,连接数据库是否成功
class Model {
constructor(app) {
this.connect();
}
connect(){
this.sequelize = new Sequelize('marron', 'root', 'example', {
host: 'localhost',
dialect: 'mysql'
})
}
testSQL() {
this.sequelize
.authenticate()
.then(() =>{
console.log('Connect has been established successfully.');
})
.catch(err =>{
console.error('Unable to connect to the database:', err);
})
}
}
看到这句话时,说明数据库连接成功了
表模型
- sequelize提供的接口如下
const User = sequelize.define('user', {
// 属性
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
},
{
// 参数
}
});
- 加到Model层的addTableUser中
class Model{
addTable = {
user: async () => {
const User = this.sequelize.define('user', {
// 属性
name: {
type: Sequelize.STRING,
allowNull: false
},
date: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
});
// 同步到数据库
User.sync({ force: true })
}
}
}
- 然后在Model的构造函数中调用一次
class Mode {
constructor(app) {
this.addTable.user();
}
}
插入一条数据到表中
- 首先要有User表的结构
- 暂时写在Model类的User方法中
class Model () {
constructor(app) {
}
User() {
return this.sequelize.define('user', {
// 属性
name: {
type: Sequelize.STRING,
allowNull: false
},
date: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
})
}
}
- 写添加user的方法
- 写在add属性下面
class Model () {
add = {
user: async (person) => {
const User = this.User();
User.create(person);
// 同步新增用户
this.sequelize.sync();
}
}
}
然后在constructor
里面运行一次this.add.user({name:'marron'})
查询数据
class Model {
find = {
user: async () => {
const User = this.User();
return await User.findAll();
}
}
}
给Service提供服务
- 前面完成了连接数据库、创建表、往表内插入数据、查询数据的接口
- 下面就是在Model中写一个index方法,给Service层中
let data = awati model.index();
提供服务
class Model () {
async index() {
return await this.find.user();
}
}
总代码如下
const koa = require('koa');
const koaRouter = require('koa-router');
class Mar {
constructor(conf) {
this.$app = new koa(conf); // 相当于koa的实例
this.$router = new koaRouter(); // 相当于koa-router的实例
this.model = new Model(this);
this.service = new Service(this);
this.controller = new Controller(this);
this.router = new Router(this);
}
listen(port) {
this.$app.listen(port, async () => {
console.log(`[mar]Server is running at http://localhost:${port}`);
})
}
}
class Router {
constructor(app) {
const { controller, $router, $app } = app;
$router.get('/', controller.index);
$app.use($router.routes());
}
}
class Controller {
constructor(app) {
const { service } = app;
console.log('Controller:', service.test());
Controller.prototype.service = service;
}
test() {
return 'Controller for Router'
}
async index(ctx) {
const service = Controller.prototype.service;
ctx.body = await service.index();
}
}
class Service {
constructor(app) {
const { model } = app;
Service.prototype.model = model;
}
test() {
return 'Service for Controller'
}
async index() {
const model = Service.prototype.model;
let data = await model.index();
data.age = '20';
data.remarks = 'forever 18';
return data;
}
}
const Sequelize = require('sequelize');
class Model {
constructor(app) {
this.connect();
}
// 给其他层的测试函数
test() {
return "Model for Service"
}
// 连接数据库的函数
connect() {
this.sequelize = new Sequelize('marron', 'root', 'example', {
host: 'localhost',
dialect: 'mysql'
})
}
// 测试是否连接成功
testSQL() {
this.sequelize
.authenticate()
.then(() => {
console.log('Connect has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
async index() {
return await this.find.user()
}
addTable = {
user: async () => {
const User = this.sequelize.define('user', {
// 属性
name: {
type: Sequelize.STRING,
allowNull: false,
},
date: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
});
User.sync({ force: true })
}
}
User() {
return this.sequelize.define('user', {
// 属性
name: {
type: Sequelize.STRING,
allowNull: false,
},
date: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
});
}
add = {
user: async (person) => {
const User = this.User();
User.create(person);
// 同步新增用户
this.sequelize.sync();
}
}
find = {
user: async () => {
const User = this.User();
return await User.findAll();
}
}
}
module.exports = Mar;