之前使用了基于koa2的MVC结构的 egg 框架,大概理解是egg的使用规范。所以这里我们也简单的实现基于koa2的MVC结构。
目录结构为:
mvc的基本加载流程也是:
koa2 --> app --> 引入config ---> 引入model ---> 引入server ---> 引入controller ---> 实列化 ---> 挂载到ctx ---> ctx全局使用复制代码
以上就是mvc基本的思路。下边来看核心代码:
//cegg.js
const Koa = require('koa');
const Router = require('koa-router');
const routerModel = require('./router');
const { initController, initServer, initModel } = require('./loader');
class cf{
constructor(){
this.app = new Koa();
initModel(this);
initServer(this);
initController(this);
const Server = this.servers;
const Controller = this.controllers;
this.app.use(async (ctx, next) => {
ctx.Server = Server;
await next();
});
const router = new Router();
const routerObj = routerModel({ Server, Controller, router });
this.app.use(routerObj.routes()).use(routerObj.allowedMethods());
}
start(port){
this.app.listen(port, ()=>{
console.log('server is starting........!');
});
}
}
module.exports = new cf();复制代码
以上是koa2 的 http 服务实现,服务ctx的挂载。
const path = require('path');
const fs = require('fs');
const Sequelize = require('sequelize');
function load(dir, fn){
const url = path.resolve(__dirname, dir);
const files = fs.readdirSync(url);
files.forEach(file => {
if(file.endsWith('.js')){
const filename = file.replace('.js', '');
const fileModel = require(url+'/'+filename);
fn(filename, fileModel);
}
});
}
function initController(app){
app.controllers = {};
load('../controller', (filename, controller)=>{
app.controllers[filename] = new controller();
});
return app;
}
function initServer(app){
app.servers = {};
load('../server', (filename, server)=>{
app.servers[filename] = new server(app.models);
});
return app;
}
function initModel(app){
load('../config', (filename, config) => {
app.models = {};
load('../model', (filename, model)=>{
const sequelize = new Sequelize(config.db);
app.models[filename] = model({ sequelize, Sequelize });
});
return app;
})
}
module.exports = { initController, initServer, initModel };复制代码
以上是controller,server, model 的文件加载
module.exports = app => {
const { Controller, router } = app;
router.get('/', Controller.home.home);
return router;
}复制代码
路由及对应的controller方法。对以上mvc的应用。
//controller/home.js
class home{
async home(ctx, next){
const res = await ctx.Server.server.userInfo();
ctx.body = res;
}}
module.exports = home;
//server/server.js
class server{
constructor(model){
this.model = model;
}
async userInfo(){
try{
return this.model.User.findAll();
}catch(error){
console.log(error);
}
}}
module.exports = server;
//model/user.js
module.exports = app => {
const { sequelize, Sequelize } = app;
const User = sequelize.define('user',{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
unique: true
},
username: {
type: Sequelize.STRING,
field: 'username'
},
email:{
type: Sequelize.STRING
}
},{
freezeTableName: true
});
return User;
};复制代码
这样就是实现对数据的访问了。
以上就是我自己对koa2实现mvc自己的思路和理解,同时向egg致敬,也欢迎各路大神指正和批评。完整请查看 github