-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
115 lines (93 loc) · 2.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const koa = require("koa");
const koaBody = require("koa-body");
const Pool = require('pg').Pool
module.exports = function(options) {
function query(pool, sql) {
return new Promise((resolve, reject) => {
pool.query(sql, function(error, results) {
if (error) reject(error);
let rows = results.rows;
resolve({
rows
});
});
});
}
/**
* config Object
* host: "localhost",
* user: "root",
* password: "12345678",
* database: "test"
*
* 详细 config 配置查看 https://github.com/mysqljs/mysql#connection-options
*/
config = {
host: options.host || 'localhost',
port: options.port || 5432,
user: options.user || 'sa',
database: options.database || 'postgres',
password: (options.password + '') || '123456'
}
const port = options.http_port || "5555";
const pool = new Pool(config);
const app = new koa();
app.use(
koaBody({
multipart: true
})
);
app.use((ctx, next)=>{
return next()
})
app.use(async (ctx, next) => {
if (ctx.path.indexOf("/api/query") === 0) {
let params = ctx.request.body;
let sql = params.sql;
try {
let data = await query(pool, sql);
return (ctx.body = data.rows);
} catch (err) {
return (ctx.body = {
errcode: 400,
message: err.message
});
}
}
return await next();
});
app.use(async ctx => {
let result
try{
result = await query(pool, "SELECT schemaname,tablename FROM pg_tables");
}catch(err){
return ctx.body = err.message
}
let tableHtml = [];
result.rows.forEach((item, index) =>
tableHtml.push(
"<tr><td> " + (index + 1) + " </td><td>" + item.schemaname + '.' + item.tablename + "</td></tr>"
)
);
ctx.body = require('./view')(tableHtml, port);
});
app.listen(port, function() {
console.log("服务启动成功, 请访问 “http://127.0.0.1:" + port + '"\n');
});
app.on('error', async (err, ctx, next) => {
// TODO logger errStack
console.error(err.message);
});
};
var fs = require('fs')
var util = require('util')
var logPath = 'upgrade.log'
var logFile = fs.createWriteStream(logPath, { flags: 'a' })
console.log = function() {
logFile.write(util.format.apply(null, arguments) + '\n')
process.stdout.write(util.format.apply(null, arguments) + '\n')
}
console.error = function() {
logFile.write(util.format.apply(null, arguments) + '\n')
process.stderr.write(util.format.apply(null, arguments) + '\n')
}