说明
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类 - 初始化
class Mar {
constructor ( app ) {
console. log ( 'Model ok' ) ;
}
test ( ) {
return 'Model for Service'
}
async index ( ) {
return {
name: 'marron'
}
}
}
此时启动服务器,访问http://localhost:3000
Model类-操作数据库
连接数据库
const sequelize = new Sequelize ( 'marron' , 'root' , 'example' , {
host: 'localhost' ,
dialect: 'mysql'
} )
sequelize
. authenticate ( )
. then ( ( ) => {
console. log ( 'Connect has been established successfully.' ) ;
} )