mysql - node express 數(shù)據(jù)操作相關(guān)的邏輯怎樣封裝更合理?
問題描述
先上目錄結(jié)構(gòu)
路由層代碼 router/
index.js
'use strict';module.exports = function (app) { app.get(’/’, function (req, res, next) {res.send(’Hello node-express World!’);next(); }); // 具體的業(yè)務(wù)請求路由配置 app.use(’/user’, require(’./user’)); // 404 page ejs渲染報錯,暫時不管 app.use(function (req, res) {if (!res.headersSent) { res.status(404); // res.status(404).render(’../view/404’);} });};
user.js
'use strict';var express = require(’express’);var router = express.Router();//mysqlvar user_pool = require('../mysql/user');// 該路由使用的中間件 timeLogrouter.use(function timeLog(req, res, next) { console.log(’Time: ’, Date.now()); next();});// 定義網(wǎng)站主頁的路由router.get(’/’, function (req, res) { // console.log(req); res.send(req.query || {});});// 查詢用戶信息router.post(’/infos’, function (req, res) { console.log(req.body); user_pool.query('select * from user where name=1104', function (data) {console.log('===============user query callback==========');console.log(data);res.send(data); });});//moremodule.exports = router;
數(shù)據(jù)層代碼 mysql/ mysql_pool.js
/** * Created by xiaogang on 2017/4/5. */'use strict';var config = require(’config-lite’);var mysql = require(’mysql’);var pool = mysql.createPool(config.mysql_pool);module.exports = pool;
user.js
/** * Created by xiaogang on 2017/4/5. */'use strict';var pool = require('./mysql_pool');exports.query = function (sql, callback) { pool.query(sql, function (error, results, fields) {if (error) throw error;callback(JSON.parse(JSON.stringify(results))); });}exports.update = function (sql, callback) { pool.query(sql, function (error, results, fields) {if (error) throw error;callback(JSON.parse(JSON.stringify(results))); });}
前端調(diào)用:zepto(jquery) 的ajax
問題:不知道各位經(jīng)常寫后臺的認為這樣封裝可行不?希望多多吐槽。
前端開發(fā)轉(zhuǎn)node,目前只能封裝到這一步,后面要上項目的,還望多多指教。
問題解答
回答1:百度搜索sequelize,可以使用這個orm來操作數(shù)據(jù)庫,雖然性能方面會有些一影響,但是使用方便
相關(guān)文章:
1. 淺談vue生命周期共有幾個階段?分別是什么?2. macos - mac下docker如何設(shè)置代理3. vue添加錨點,實現(xiàn)滾動頁面時錨點添加相應(yīng)的class操作4. index.php錯誤,求指點5. css3 - 這個右下角折角用css怎么畫出來?6. html5 - 一個用vue組件實現(xiàn)功能的問題7. javascript - js正則匹配小括號中的內(nèi)容8. javascript - 想在編寫weex應(yīng)用的時候使用rxjs,如何進行相關(guān)配置呢?9. javascript - 調(diào)微信分享朋友接口,出現(xiàn)下面問題,求解答,10. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請求)
