koa --- > [MVC实现之五]Model层的实现

说明


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.');
    })
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值