node.js项目改进之添加mysql模块驱动(1)

最常用的数据库mysql

说起来做php程序的时候最常用的也是mysql,说起来不只是这几种系统像asp,jsp啥的也是非常常见的。用的多的话出了问题也好解决。

使用Sequelize模块调动mysql

首先我们添加sequelize与mysql两个依赖包

npm install sequelize -save
npm install mysql -save

配置环境配置

之前我们不是配置过三个不同环境的配置文件吗,现在我们添加配置
以其中一个环境配置为例

config/development.js

原文件:

'use strict';
/**
 * 开发环境配置文件
 */
var config = {
    env: 'development', //环境名称
    port: 3001,         //服务端口号
    mysql_config: {
        //mysql数据库配置
    },
    mongodb_config: {
        //mongodb数据库配置
    },
    redis_config: {
        //redis数据库配置
    },

};
module.exports=config;

修改后的文件:

'use strict';
/**
 * 开发环境配置文件
 */
var config = {
    env: 'development', //环境名称
    port: 3001,         //服务端口号
    mysql_config: {
        //mysql数据库配置
        db_name:'node',//数据库名称
        db_user:'root',//数据库使用者名称
        db_password:'',//使用者密码
        db_host:'localhost',//地址
        db_port:'3306',//端口号
        db_prefix:'node_'//表前缀
    },
    mongodb_config: {
        //mongodb数据库配置
    },
    redis_config: {
        //redis数据库配置
    },

};
module.exports=config;

由于我为了方便我直接使用之前电脑上写PHP的WAMP集成环境中的mysql所以具体配置是如此的,具体的mysql安装和使用请看教程可以在菜鸟教程上查看具体教程。
并且我为此配置了名为node的数据库,新建一表结构为:
mysql
之后这个表我又修改表名为node_users了

写mobel通用模块。

app_need/model.js

'use strict';
//sequelize实例声明
const Sequelize = require('sequelize');
const config = require('../app_need/config');
var mysql_config = config.mysql_config;
var sequelize = new Sequelize(mysql_config.db_name, mysql_config.db_user, mysql_config.db_password, {
    host: mysql_config.db_host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});
var db_prefix = mysql_config.db_prefix;//为了节约代码向下传递表前缀
module.exports = {
    model: sequelize, db_prefix: db_prefix
};

写model层

为model层写几层目录新建model文件夹在最外层

内容像这样:
model
我们暂时分两层,
db_model层用来映射数据库,并且把大多数数据库操作进行封装,并进行无关业务的的基本验证和map映射调整。按照我们的想法表明和文件名最好对应起来
logic_model层用来书写具体的业务逻辑,调用db_model层数据,然后将每个业务模块封装供控制层调用以实现具体功能和代码的复用。

编写db_model层的users表映射

users.js
'use strict';
const Sequelize = require('sequelize');
const Rmodel=require('../../app_need/model');
const model=Rmodel.model;//此处虽然叫model但是实际上是sequelize的实例
const db_prefix=Rmodel.db_prefix;
var User=model.define(
    db_prefix+'users',{
        id:{
            type:Sequelize.INTEGER(20),
            primaryKey:true,//声明主键
            autoIncrement:true//声明自增
        },
        name:Sequelize.STRING(30),
        password:Sequelize.STRING(50)
    },{
        timestamps:false
    }
);
var user={};
//基本的增删改查
//增
user.create=function(data){
var the_data=data||{};
return  (async (ctx,next) => {
    var user = await  User.create(the_data);
    console.log('created: ' + JSON.stringify(user));
})();
}
//查
user.select=function(where){
var the_where=where||{};
return (async (ctx,next) => {
    var users = await User.findAll({
        where: the_where
    });
    console.log(`find ${users.length} user:`);
    for (let user of users) {
        console.log(JSON.parse(JSON.stringify(user)));
    }

})();
}
//改
user.updata=function(where,data){
var the_where=where||{};
var the_data=data||{};
return (async (ctx,next) => {
    var users = await User.findAll({
        where: the_where
    });
    for(let user of users){
user.name=the_data.name;
user.password=the_data.password;
await user.save();
    }

})();
}
//删
user.delete=function(where){
var the_where=where||{};
return (async (ctx,next) => {
     var users = await User.findAll({
        where: the_where
    });
    for(let user of users){
   await user.destroy();
    }


})();
}
module.exports=user;

现在这个表就和users表对应上了,而且拥有了基本的增删改查功能。可以供logic_model调用,但是想一想每有一个表就要重复这么多代码也是头疼,之后我们可以抽象出一个类来,让每个映射模块继承,只要这个类写好了,可以方便的节省代码了。这个类放到下一篇博客写吧。

编写logic_model下的user功能表

这个表暂时没有具体的业务逻辑只是简单的演示一下

user.js
'use strict';
var db_user = require('../../mobel/db_model/users');
var f = {};
f.f1 = function () {
    db_user.create({ name: '神1', password: 'abcd' });
}
f.f2 = function () {
    db_user.select({ name: '神1', password: 'abcd' });
}
f.f3=function(){
    db_user.updata({ name: '神1', password: 'abcd' },{name:'神2',password:'hahahah'});
}
f.f4=function(){
    db_user.delete({ name: '神1', password: 'abcd' });
}
module.exports = f;

假设我们的每个业务就是执行一次里面的增删改查其中的一种于是抽象的业务就是这样的。
然后我们要最终使用这些业务写到控制器去,但是我们现在还没将控制器单独拿出来只是和路由放在一起的所以我们就在routes/index.js下使用

routes/index.js承载业务

index.js
var router = require('koa-router')();
var view = require('../app_need/view');
var user=require('../mobel/logic_model/user');
router.get('/', async function (ctx, next) {
  var v = view.render('index.html', { name: '小明' });
   var post= ctx.body;
   var get= ctx.query;
user.f1();
user.f2();
user.f3();
user.f4();
    ctx.body = v;
})
module.exports = router;

我们要分别测试这四个业务。
就到这里。
最终项目地址:https://github.com/jijuxie/koa2_all.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值