日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

發布時間:2023/12/10 c/c++ 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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類里面
  • 進入Model類的時候,連接到數據庫
  • 有一個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;

    總結

    以上是生活随笔為你收集整理的koa --- [MVC实现之五]Model层的实现的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。