koa ---> [Achieving MVC five] Model layer implemented

Explanation


Service Layer

  • Or from the business, Service layer is the caller, call mode and call the Service layer as Layer Controller
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 class

  • Design principle is that passing parameters between the different layers, by Mar class.
  • Model need to mount it in the class Mar
  • Mar rewritten as follows Class
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 - initialization

  • New classes as follows Mar
class Mar {
	constructor ( app ) {
		console.log('Model ok');
	}
	test() {
		return 'Model for Service'
	}
	async index() {
		return {
			name: 'marron'
		}
	}
}
  • At this time the server is started, visithttp://localhost:3000
    Here Insert Picture Description

Model class - operational database

  • Preparing a database, in accordance with the docker-compose.yml Construction container.
  • Browser to open the management page
    Here Insert Picture Description
    Note: The password is example
  • New Database marron
    Here Insert Picture Description
    Here Insert Picture Description
  • When ready, connect to the database, and test

Connect to the database

  • Interface Sequelize library provides the following
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);
    });
  • Wrote Model class inside
  1. When entering the Model class, connect to the database
  2. There is a testSQL method for testing whether a successful connection to the database
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);
			})
	}
}

Here Insert Picture Description
When you see this sentence, it indicates that the database connection is successful


Table model

  • It provides the following interfaces sequelize
const User = sequelize.define('user', {
	// 属性
	firstName: {
		type: Sequelize.STRING,
		allowNull: false
	},
	lastName: {
		type: Sequelize.STRING
	},
	{
		// 参数
	}
});
  • Model layer applied in 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 })
		}
	}
}
  • Then called once in the constructor's Model
class Mode {
	constructor(app) {
		this.addTable.user();
	}
}

Here Insert Picture Description


Inserting data into a table

  • User must first have the structure of the table
  • Temporarily written in the User class method Model
class Model () {
	constructor(app) {
	}
	User() {
		return this.sequelize.define('user', {
			// 属性
			name: {
				type: Sequelize.STRING,
				allowNull: false
			},
			date: {
				type: Sequelize.DATE,
				defaultValue: Sequelize.NOW
			}
		})
	}
}
  • Write method of adding user
  • Write add the following attributes
class Model () {
	add = {
		user: async (person) => {
			const User = this.User();
			User.create(person);
			// 同步新增用户
			this.sequelize.sync();
		}
	}
}

Then constructorrun inside athis.add.user({name:'marron'})
Here Insert Picture Description

Query data

class Model {
	find = {
		user: async () => {
			const User = this.User();
			return await User.findAll();
		}
	}
}

Service to provide services

  • Front connection completion database, creating tables, inserting data into the tables, query data interface
  • Here is a write index method in the Model, Service layer to let data = awati model.index();provide services
class Model () {
	async index() {
		return await this.find.user();
	}
}

Total code as follows

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;
Published 177 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/piano9425/article/details/103447909