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

说明

  • 上一篇: 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类里面
  1. 进入Model类的时候,连接到数据库
  2. 有一个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;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/250437.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于字符串 --java

这是在杭电上做一道水题时发现的,挺不错,写下了分享一下 http://acm.hdu.edu.cn/showproblem.php?pid2072 这里我用了两种方法,参考大佬的,一个是list实现类,一个是用set框架 import java.util.*;public class Main {…

三元表达式 列表递推 生成器表达式

#!/use/bin/python# -*- conding:utf-8 -*-# def my_max(x,y):# if x > y : #>必须紧凑# return x# else:# return y# x 10# y 20# res x if x>y else y# print(res)# name input(>>>:).strip()# res 漂亮小姐姐 if name 汪妍…

node --- 模拟事件的异步

事件 在前端浏览器最常见的就是页面交互事件本质是发布/订阅设计模式 目标 对象使用add方法订阅事件。使用emit发布消息 订阅事件 添加触发事件的一个唯一字符串,以及对应的处理函数先初始化事件对象 class Event {constructor(){this.events {};} }订阅在订阅事件的时候,…

Vue-webpack项目配置详解

Vue-webpack项目配置详解 1、首先我们在构建vue项目后,就得先了解vue的项目结构 ├── build --------------------------------- webpack相关配置文件 │ ├── build.js --------------------------webpack打包配置文件 │ ├── check-versions.js ----…

浅谈PHP面向对象编程(九)

9.0 设计模式 在编写程序时经常会遇到一此典型的问题或需要完成某种特定需求,设计模式就是针对这些问题和需求,在大量的实践中总结和理论化之后优选的代码结构编程风格,以及解决问题的思考方式。 设计模式就像是经典的棋谱。不同的棋局&#…

javascript --- Object.create的阅读

说明 今天阅读koa源码时,遇到Object.create,感觉对这个概念有点生疏,于是打开了MDN进行重新梳理传送门 Object.create() 直接套用官网的栗子 const person {isHuman: false,printIntroduction: function () {console.log(My name is ${this.name}. Am I human? ${this.i…

python 12306 车次数据获取

python 12306 车次数据获取 ssl._create_default_https_context ssl._create_default_https_context train_data 2018-10-20 headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36,…

Annotation 注解

Annotation分为两种,第一种为系统内置注解,第二种为自定义注解。系统内置注解:例如Override,Dprecated自定义注解:定义格式为 【public】 interface Annotation名称{数据类型 变量名称();}其中数据类型和变量自定义,不…

node --- [node接口阅读]cluster的使用

目标 在主进程中完成以下事情: 每隔1秒钟输出,当前请求的数量创建等同于CPU数量的进程对每个进程施加一个处理函数,用于统计请求的数量 在各个CPU的进程中完成以下事情 监听8000端口的请求,并返回最简单的信息发送事件,以触发主进程中施加的事件处理函数 前置知识 process…

洛谷P4777 【模板】扩展中国剩余定理(EXCRT)

传送门 关于excrt 1 //minamoto2 #include<iostream>3 #include<cstdio>4 #define int long long5 using namespace std;6 #define getc() (p1p2&&(p2(p1buf)fread(buf,1,1<<21,stdin),p1p2)?EOF:*p1)7 char buf[1<<21],*p1buf,*p2buf;8 int …

adb shell dumpsys

获取某个包的信息: adb shell dumpsys package <PACKAGE_NAME> 包含了Activity、Service和Receiver中的Action信息。注册的Provider Permission信息&#xff0c;被授予的权限信息 查看AndroidManifest.xml&#xff1a; aapt dump xmltree xxx.apk AndroidManifest.xml a…

docker --- 梳理 Dockerfile docker-compose.yml

docker run -p 80:80 -v $PWD/www:/usr/share/nginx/html nginx 参数说明: 1.docker run nginx: 感觉镜像(images)生成本地的容器 2.-p 80:80: 容器的80端口和本地的80端口的映射 3.-v:将本地的,当前文件夹下的www文件夹映射容器路径为/usr/share/nginx/html的文件夹下 [注:]…

python接口测试框架实战与自动化进阶(三)

python接口测试框架实战与自动化进阶 一、持续集成 1、持续集成环境搭建 1&#xff09;安装Jenkins 官网下载后直接安装&#xff1a;https://jenkins.io/ 终端直接安装及启动&#xff1a;java -jar jenkins.war 2&#xff09;Jenkins用于&#xff1a; 持续、自动地构建/测试软件…

配置 --- 将本地项目部署到阿里云上

说明: 项目代码学习地址项目前端使用了nginx代理后端使用express框架使用PM2部署后端使用mongoDB进行持久化nginx、express、PM2、mongoDB等,部署在docker中.项目使用 .sh 文件进行一键式启动 本地启动项目 1.先从github上拉取代码 git clone https://github.com/Lizhhhh/L-n…

前台获取json未定义问题之两种常用解决办法

来自博客园的一位朋友解答: 为什么要 eval这里要添加 “("("data")");//”呢&#xff1f; 原因在于&#xff1a;eval本身的问题。 由于json是以”{}”的方式来开始以及结束的&#xff0c;在JS中&#xff0c;它会被 当成一个语句块来处理&#xff0c;所以必…

layui --- [结构优化]参数优化

待优化的代码如下 以上代码,在至少10个页面中重复应用.如果要修改某个功能,就得在至少10个页面中修改.给后期维护带来了极大的不便.关键是这些信息都是在编程中不需要看见的.放在开始每次都要滑过它,太浪费时间了. [注意代码行数,后期会用到] 参数分类 声明类: 对layui模块引…

mysql带条件查询,联表查询

---恢复内容开始--- 1,用于设定所select出来的数据是否允许出现重复行&#xff08;完全相同的数据行&#xff09; all&#xff1a;允许出现——默认不写就是All&#xff08;允许的&#xff09;。 distinct&#xff1a;不允许出现——就是所谓的“消除重复行” 2&#xff0c;whe…

day11-元组与字典

1、元组Tuple与列表类似&#xff0c;不同之处在于元组的元素不能修改。 元组使用小括号&#xff0c;列表使用中括号。元组可以查询&#xff0c;可以使用内置函数count、index。但是不能修改、增加、删除&#xff08;儿子不能&#xff0c;孙子有可能&#xff09;。name (a,a,b)…

算法 --- [map的使用]求最大和谐子序列

说明 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。 现在&#xff0c;给定一个整数数组&#xff0c;你需要在所有可能的子序列中找到最长的和谐子序列的长度。 输入: [1,3,2,2,5,2,3,7] 输出: 5 原因: 最长的和谐数组是&#xff1a;[3,2,2,2,3]. 思路 创…

vue问题四:富文本编辑器上传图片

vue使用富文本编辑器上传图片&#xff1a; 我是用的是wangEditor 富文本编辑器 demo:http://www.wangeditor.com/ 1).安装依赖:npm install wangeditor 2).我自己是创建了一个组件这样再用到的时候可以直接调用&#xff08;可能有更简单的方法&#xff09; <template lang&q…