-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.js
110 lines (92 loc) · 2.4 KB
/
app.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
var http = require("http");
var mysql = require("mysql");
// connect to the mysql database
var pool = mysql.createPool({
connectionLimit: 100, //important
host: 'localhost',
user: 'js-crud-api',
password: 'js-crud-api',
database: 'js-crud-api',
charset: 'utf8',
debug: false
});
// ensure request has database connection
var withDb = function (handler) {
return function (req, resp) {
pool.getConnection(function (err, connection) {
if (err) {
resp.writeHead(404)
resp.end(err);
return;
}
req.db = connection;
handler(req, resp);
});
}
};
// ensure request has (post) body
var withBody = function (handler) {
return function (req, resp) {
var input = "";
req.on("data", function (chunk) {
input += chunk;
});
req.on("end", function () {
req.body = input;
handler(req, resp);
});
}
};
// main web handler
var server = http.createServer(withDb(withBody(function (req, resp) {
// get the HTTP method, path and body of the request
var method = req.method;
var request = req.url.replace(/^[\/]+|[\/]+$/g, '').split('/');
try {
var input = JSON.parse(req.body);
} catch (e) {
var input = {};
}
// retrieve the table and key from the path
var table = req.db.escapeId(request.shift());
var key = req.db.escape(request.shift());
// create SQL based on HTTP method
var sql = '';
switch (req.method) {
case 'GET':
sql = "select * from " + table + (key ? " where id=" + key : '');
break;
case 'PUT':
sql = "update " + table + " set ? where id=" + key;
break;
case 'POST':
sql = "insert into " + table + " set ?";
break;
case 'DELETE':
sql = "delete " + table + " where id=" + key;
break;
}
// execute SQL statement
req.db.query(sql, input, function (err, result) {
// stop using mysql connection
req.db.release();
// return if SQL statement failed
if (err) {
resp.writeHead(404)
resp.end(err);
return;
}
// print results, insert id or affected row count
resp.writeHead(200, {
"Content-Type": "application/json"
})
if (req.method == 'GET') {
resp.end(JSON.stringify(result));
} else if (method == 'POST') {
resp.end(JSON.stringify(result.insertId));
} else {
resp.end(JSON.stringify(result.affectedRows));
}
});
})));
server.listen(8000);