选用更加易懂的设计模式封装node-mysql

js的三大特性之一封装性相信大家都是知道的。可是封装函数应该如何选用合理的设计模式呢。

比如我们在用axios的发送ajax的时候可以写成axios.post().then().catch()的写法。

这种链式的写法,让语句变得更加清晰明了。

同样的我们队node-mysql的语句封装也可以模仿这种设计模式(称为构造模式)

var mysql      = require('mysql');
function connect(database){
return new conector(database)
}
class conector{
constructor(database){
this.connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '****',
  database : database
});
this.connection.connect();
}
query(sql){
var that=this;
this.connection.query(sql, function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
  that.then(error, results, fields)
});
}
then(error, results, fields){
fn(error, results, fields)
this.connection.end();
}
}
module.exports=connect;

这样:当我们const connect=require(该模块路径后)

则可以使用connect(数据库).query(sql语句).then(fun(){成功后方法})

比较清晰的设计模式,当然还可以依次类推,将host或user设置成变量

大家可以想象一下如何封装一个可以这样执行的函数

connect(数据库).host(接口名).user(用户名).query(sql语句).then(成功后方法).catch(失败后方法).end(关闭connect连接)

你可能感兴趣的:(52,nodejs,设计模式)