私信发送成功
检测到您已登录开源中国,是否 一键登录码云
Watch Star Fork

oyhk / mkfree-blogNodeJS

1.重构整个域模型 2.添加co 和 promise 使用,解决异步调用问题 3.使用es6语法
oyhk 提交于   master
commit 0b19be072d6a7c72ba6d9f7b9f00efedc263ab2f
1 parent 73f60d1e65
var mysql = require('mysql');
var config = {};
+// 开发环境
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined) {
- config.mysqlPool = mysql.createPool({
+ config.mysqlPool = mysql.createPool({
connectionLimit: 100, //important
host: 'localhost',
user: 'root',
@@ -11,8 +12,9 @@ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined
});
}
 
-if(process.env.NODE_ENV === 'production'){
- config.mysqlPool = mysql.createPool({
+// 生产环境
+if (process.env.NODE_ENV === 'production') {
+ config.mysqlPool = mysql.createPool({
connectionLimit: 100, //important
host: 'localhost',
user: 'root',
var config = require('../config');
 
+
/**
- * 父类
- * @constructor
+ * 域模型基类 这里封装了一系列的 mysql 操作行为
+ *
+ * 充血模型设计
+ *
*/
-function Base() {
-
-}
+class Base {
 
-Base.query = function (sql, params, callback) {
- config.mysqlPool.getConnection((err, connection)=> {
- if (err) {
- connection.release();
- console.log("Error in connection database");
- return;
- }
- console.log('connected as id ' + connection.threadId);
- console.log(`base sql : ${sql}`);
- connection.query(sql, params, function (err, rows) {
- connection.release();
- if (!err) {
- callback(rows);
- }
- });
-
- connection.on('error', function (err) {
- console.log("Error in connection database");
- return;
- });
- });
-};
-
-Base.prototype.findAll = function (callback) {
- var tableName = this.constructor.name.replace(/([A-Z])/g, "_$1").toLowerCase();
- if (tableName.indexOf("_") == 0) {
- tableName = tableName.substring(1);
+ findOne(id) {
+ let sql = `select * from ${this.tableName} where id = ?`;
+ let params = [id];
+ return this.execute(sql, params);
}
- var sql = `select * from ${tableName}`;
- Base.query(sql, [], (rows)=> {
- callback(rows);
- });
-};
 
-Base.prototype.findOne = function (id, callback) {
- var tableName = this.constructor.name.replace(/([A-Z])/g, "_$1").toLowerCase();
- if (tableName.indexOf("_") == 0) {
- tableName = tableName.substring(1);
- }
- var sql = `select * from ${tableName} where id = ?`;
- Base.query(sql, id, (rows)=> {
- callback(rows[0]);
- });
-};
+ /**
+ * 执行sql 并且返回 promise 对象
+ * @param sql
+ * @param sqlParams
+ * @returns {Promise}
+ */
+ execute(sql, sqlParams) {
+ let queryParams = [sql, sqlParams];// 代表pool.query(sql,values,cb) 三个参数,如有疑问可以查看一下 pool.query的源代码
+ let p = new Promise((resolve, reject) => {
+ queryParams.push((err, rows) => {
+ if (err) {
+ console.log(err);
+ reject(err);
+ } else {
+ resolve(rows);
+ }
+ });
+ // apply 这里是利用反射 调用 pool.query(sql,values,cb)
+ config.mysqlPool.query.apply(config.mysqlPool, queryParams);
+ });
 
-Base.prototype.delete = function (id, callback) {
- var tableName = this.constructor.name.replace(/([A-Z])/g, "_$1").toLowerCase();
- if (tableName.indexOf("_") == 0) {
- tableName = tableName.substring(1);
+ return p;
}
- var sql = `delete from ${tableName} where id = ?`;
- Base.query(sql, id, (rows)=> {
- callback(rows);
- });
-};
-
-Base.prototype.update = function (sql, params, callback) {
- Base.query(sql, params, (rows)=> {
- callback(rows);
- });
-};
-Base.prototype.save = function (sql, params, callback) {
- Base.query(sql, params, (rows)=> {
- callback(rows);
- });
-};
+}
 
-Base.prototype.find = function (sql, params, callback) {
- Base.query(sql, params, (rows)=> {
- callback(rows);
- });
-};
 
module.exports = Base;
\ No newline at end of file
var Base = require('./Base');
 
-function BlogPost() {
- BlogPost.super_.apply(this, arguments);
-}
+class BlogPost extends Base {
+ constructor() {
+ super();
+ super.tableName = 'blog_post';
+ }
 
-// 继承Base
-BlogPost.super_ = Base;
+ findByOldId(oldId){
+ let sql = "select * from blog_post bp where bp.old_id = ?";
+ let params = [sql,[oldId]];
+ return super.execute(params);
+ }
 
-BlogPost.prototype = Object.create(Base.prototype, {
- constructor: {
- value: BlogPost,
- enumerable: false
+ saveByParams(params){
+ let sql = "insert into blog_post(title,content_html,content_markdown,user_id) values (?,?,?,?)";
+ return super.execute(sql,params)
}
-});
+}
 
-module.exports = BlogPost.prototype;
\ No newline at end of file
+module.exports = BlogPost;
\ No newline at end of file
@@ -7,6 +7,7 @@
},
"dependencies": {
"body-parser": "~1.15.1",
+ "co": "^4.6.0",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
var express = require('express');
-var router = express.Router();
+var BlogPost = require('../domain/BlogPost');
+var co = require('co');
 
-var blogPost = require('../domain/BlogPost');
+var router = express.Router();
 
+var blogPost = new BlogPost();
/**
* 博客发布页
*/
@@ -17,10 +19,13 @@ router.post('/save', function (req, res, next) {
return;
}
 
- let params = [req.body.title, req.body.contentHtml, req.body.contentMarkdown,1];
- blogPost.save("insert into blog_post(title,content_html,content_markdown,user_id) values (?,?,?,?)", params, (result)=> {
+ let params = [req.body.title, req.body.contentHtml, req.body.contentMarkdown, 1];
+ co(function *() {
+ var result = yield blogPost.saveByParams(params);
res.redirect(`/posts/${result.insertId}`);
});
+
+
});
 
 
var express = require('express');
var router = express.Router();
+var config = require('../config');
+var co = require('co');
+var BlogPost = require('../domain/BlogPost');
 
-var blogPost = require('../domain/BlogPost');
 
+// 看什么时候搞一个spring 的 ioc
+var blogPost = new BlogPost();
/**
* 博客详情页
*/
router.get('/:id', function (req, res, next) {
- let sql = '';
- if (isNaN(req.params.id)) {
- sql = "select * from blog_post bp where bp.old_id = ?";
- } else {
- sql = "select * from blog_post bp where bp.id = ?"
- }
- blogPost.find(sql, req.params.id, (result)=> {
+ // 这里使用 co 和 promise 解决异步回调问题
+ co(function*() {
+ let result;
+ if (isNaN(req.params.id)) {
+ result = yield blogPost.findByOldId([req.params.id]);
+ } else {
+ result = yield blogPost.findOne(req.params.id);
+ }
res.render('show', {blogPost: result[0]});
});
-});
-
-
 
+});
 
module.exports = router;
var express = require('express');
-var router = express.Router();
+var co = require('co');
+var BlogPost = require('../domain/BlogPost');
 
-var blogPost = require('../domain/BlogPost');
+var router = express.Router();
 
 
+// 看什么时候搞一个spring 的 ioc
+var blogPost = new BlogPost();
/* GET home page. */
router.get('/', function (req, res, next) {
- blogPost.findOne(1,(result)=> {
- res.render('index', {blogPost: result});
+ co(function *() {
+ let focusBlogPost = yield blogPost.findOne(1);
+ res.render('index', {focusBlogPost: focusBlogPost[0]});
});
});
 
@@ -33,9 +33,23 @@ block content
div(class="container blog-new ")
div(class="row")
div(class="jumbotron")
- h3 #{blogPost.title}
- p #{blogPost.summary}
+ h3 #{focusBlogPost.title}
+ p #{focusBlogPost.summary}
p
- a(class="btn btn-primary" href='/posts/#{blogPost.id}') 详情
+ a(class="btn btn-primary" href='/posts/#{focusBlogPost.id}') 详情
div(class="container blog-list")
- div(class="row")
\ No newline at end of file
+ div(class="row")
+ div(class="col-lg-3")
+ div(class="thumbnail")
+ img(data-src="holder.js/300x300" alt="...")
+ div(class="caption")
+ h3 Thumbnail label
+ p ...
+ p <a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
+ div(class="col-lg-3")
+ div(class="thumbnail")
+ img(data-src="holder.js/300x300" alt="...")
+ div(class="caption")
+ h3 Thumbnail label
+ p ...
+ p <a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
\ No newline at end of file

登录 后才可以发表评论