Explorar el Código

change return format

Dotos hace 9 años
padre
commit
7d557a79bc
Se han modificado 8 ficheros con 152 adiciones y 54 borrados
  1. 10 4
      app.js
  2. 39 37
      bin/www
  3. 12 1
      routes/netease.js
  4. 19 8
      routes/v1.js
  5. 69 2
      utils/dbUtils.js
  6. 1 0
      utils/logUtils.js
  7. 1 1
      views/layout.pug
  8. 1 1
      views/welcome.pug

+ 10 - 4
app.js

@@ -106,8 +106,11 @@ if (app.get('env') === 'development') {
     app.use(function(err, req, res, next) {
         res.status(err.status || 500);
         res.send({
-            status: err.status,
-            message: err.message
+            data: {},
+            status: {
+                code: err.status,
+                message: err.message
+            }
         });
     });
 }
@@ -117,8 +120,11 @@ if (app.get('env') === 'development') {
 app.use(function(err, req, res, next) {
     res.status(err.status || 500);
     res.send({
-        status: err.status,
-        message: err.message
+        data: {},
+        status: {
+            code: err.status,
+            message: err.message
+        }
     });
 });
 

+ 39 - 37
bin/www

@@ -15,6 +15,8 @@ var http = require('http');
 var port = normalizePort(process.env.PORT || '3000');
 app.set('port', port);
 
+console.log("SESSION_SECRET:" + process.env.SESSION_SECRET);
+
 /**
  * Create HTTP server.
  */
@@ -34,19 +36,19 @@ server.on('listening', onListening);
  */
 
 function normalizePort(val) {
-  var port = parseInt(val, 10);
+    var port = parseInt(val, 10);
 
-  if (isNaN(port)) {
-    // named pipe
-    return val;
-  }
+    if (isNaN(port)) {
+        // named pipe
+        return val;
+    }
 
-  if (port >= 0) {
-    // port number
-    return port;
-  }
+    if (port >= 0) {
+        // port number
+        return port;
+    }
 
-  return false;
+    return false;
 }
 
 /**
@@ -54,27 +56,27 @@ function normalizePort(val) {
  */
 
 function onError(error) {
-  if (error.syscall !== 'listen') {
-    throw error;
-  }
-
-  var bind = typeof port === 'string'
-    ? 'Pipe ' + port
-    : 'Port ' + port;
-
-  // handle specific listen errors with friendly messages
-  switch (error.code) {
-    case 'EACCES':
-      console.error(bind + ' requires elevated privileges');
-      process.exit(1);
-      break;
-    case 'EADDRINUSE':
-      console.error(bind + ' is already in use');
-      process.exit(1);
-      break;
-    default:
-      throw error;
-  }
+    if (error.syscall !== 'listen') {
+        throw error;
+    }
+
+    var bind = typeof port === 'string' ?
+        'Pipe ' + port :
+        'Port ' + port;
+
+    // handle specific listen errors with friendly messages
+    switch (error.code) {
+        case 'EACCES':
+            console.error(bind + ' requires elevated privileges');
+            process.exit(1);
+            break;
+        case 'EADDRINUSE':
+            console.error(bind + ' is already in use');
+            process.exit(1);
+            break;
+        default:
+            throw error;
+    }
 }
 
 /**
@@ -82,9 +84,9 @@ function onError(error) {
  */
 
 function onListening() {
-  var addr = server.address();
-  var bind = typeof addr === 'string'
-    ? 'pipe ' + addr
-    : 'port ' + addr.port;
-  debug('Listening on ' + bind);
-}
+    var addr = server.address();
+    var bind = typeof addr === 'string' ?
+        'pipe ' + addr :
+        'port ' + addr.port;
+    debug('Listening on ' + bind);
+}

+ 12 - 1
routes/netease.js

@@ -14,7 +14,18 @@ router.get('/', function(req, res, next) {
         url = 'http://music.163.com/api/playlist/detail/?id=' + playlist_id;
     }
     netease_http(url, next, function(data) {
-        return res.send(data);
+        var output = {
+            data: data,
+            status: {
+                code: 200,
+                message: ''
+            }
+        };
+        if (req.query.callback) {
+            return res.jsonp(output)
+        } else {
+            return res.send(output);
+        }
     });
 });
 

+ 19 - 8
routes/v1.js

@@ -12,15 +12,20 @@ router.get('/', function(req, res, next) {
     var protocol = req.protocol;
     var originalUrl = req.originalUrl;
     var ip = req.ip.replace(/::ffff:/, '');
-    if (originalUrl == /v1/) {
+    if (originalUrl === /v1/) {
         ip2address(ip, function(data) {
             var output = {
-                status: 200,
-                IP: ip,
-                info: 'Please Set URL Like This: ' + protocol + '://' + host + '/v1/?url=http[s]://YourWantProxyUrl.com'
+                data: {
+                    IP: ip,
+                    info: 'Please Set URL Like This: ' + protocol + '://' + host + '/v1/?url=http[s]://YourWantProxyUrl.com'
+                },
+                status: {
+                    code: 200,
+                    message: ''
+                }
             };
             if (data) {
-                output['Location'] = data.area + data.location;
+                output['data']['Location'] = data.area + data.location;
             }
             return res.send(output);
         });
@@ -30,11 +35,17 @@ router.get('/', function(req, res, next) {
         url = url.indexOf('?') === -1 ? url.replace('&', '?') : url;
         url = url.indexOf('http://') === -1 ? 'http://' + url : url;
         getJSON(url, next, function(data) {
-            data['status'] = 200;
+            var output = {
+                data: JSON.parse(data),
+                status: {
+                    code: 200,
+                    message: ''
+                }
+            };
             if (req.query.callback) {
-                return res.jsonp(data);
+                return res.jsonp(output);
             } else {
-                return res.send(data);
+                return res.send(output);
             }
         });
     }

+ 69 - 2
utils/dbUtils.js

@@ -4,11 +4,42 @@ var mysql = require('mysql');
 var config = require('../configs/config').mysql_dev;
 //使用连接池
 var pool = mysql.createPool(config);
+//公共连接设置
+var commonFormat = function(callback) {
+    pool.getConnection(function(err, connection) {
+        //console.log(callback);
+        //自定义参数匹配设置
+        connection.config.queryFormat = function(query, values) {
+            if (!values) return query;
+            return query.replace(/\:(\w+)/g, function(txt, key) {
+                if (values.hasOwnProperty(key)) {
+                    return this.escape(values[key]);
+                }
+                return txt;
+            }.bind(this));
+        };
+        callback && callback(err, connection);
+    });
+};
+
 //存储
 module.exports = {
     //添加/修改数据
-    set: function(key, val) {
-
+    set: function(params) {
+        // var sql = 'select 1+1 as test';
+        // pool.query(sql, function(err, rows, fields) {
+        //     console.log(err);
+        //     console.log(rows);
+        //     console.log(fields);
+        // });
+        var sql = 'select MD5("123456") as calc';
+        commonFormat(function(err, connection) {
+            connection.query(sql, { id: 1 + 1 }, function(err, rows) {
+                //console.log(err);
+                console.log(rows);
+                console.log(rows.length)
+            });
+        });
     },
     //获取数据
     get: function(key) {
@@ -17,5 +48,41 @@ module.exports = {
     //删除数据
     del: function(key) {
 
+    },
+    //事务
+    transaction: function(params) {
+        commonFormat(function(err, connection) {
+            //Transaction Begin
+            connection.beginTransaction(function(err) {
+                if (err) throw err;
+                var keys = [];
+                var vals = [];
+                connection.query('insert into :table(' + keys.join(',') + ') values(' + vals.join(',') + ') ', params, function(err, result) {
+                    if (err) {
+                        return connection.rollback(function() {
+                            throw err;
+                        });
+                    }
+                    var insertId = result.insertId;
+                    //Transaction Next
+                    connection.query('insert into :table(' + keys.join(',') + ') values(' + vals.join(',') + ')', params, function(err, result) {
+                        if (err) {
+                            return connection.rollback(function() {
+                                throw err;
+                            });
+                        }
+                        //Transaction Commit
+                        connection.commit(function(err) {
+                            if (err) {
+                                return connection.rollback(function() {
+                                    throw err;
+                                });
+                            }
+                            console.log('Transaction Success!');
+                        });
+                    });
+                });
+            });
+        });
     }
 };

+ 1 - 0
utils/logUtils.js

@@ -1,6 +1,7 @@
 var storage = require('./dbUtils');
 module.exports = {
     print: function(params) {
+        //storage.set({});
         var arr = ['-------------------------------------'];
         // var date = new Date();
         // var month = date.getMonth() + 1;

+ 1 - 1
views/layout.pug

@@ -5,5 +5,5 @@ html
     link(rel='stylesheet', href='/static/css/style.css')
     meta( name="viewport",content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0")
     meta( name="author",content="xCss xioveliu@gmail.com")
-  body
+  body 
     block content

+ 1 - 1
views/welcome.pug

@@ -6,7 +6,7 @@ block content
             div.cover.heading #{head}
             div.cover.description #{description}<br>#{address}
             div.cover.action
-                a.btn.btn-ghost-light(href="/v1/?url=http://www.bing.com/HPImageArchive.aspx?format=js&idx=16&n=1") Quick Start
+                a.btn.btn-ghost-light(href="/v1/?url=http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1") Quick Start
 
     script(src="/static/libs/three/three.min.js")
     script(src="/static/libs/three/Projector.js")