-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress.js
178 lines (157 loc) · 5.96 KB
/
express.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
var express=require('express'),
bodyParser = require('body-parser'),
mysql=require('mysql'),
credentials=require('./credentials.json'),
app = express(),
port = process.env.PORT || 1337;
var Promise = require('bluebird');
var using = Promise.using;
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
credentials.host='ids.morris.umn.edu'; //setup database credentials
var databaseName = "schr1230";
// Created a connection pool
connectionPool = mysql.createPool(credentials); // setup the connection
// current logged in user
var currentUser='';
//
var getConnection = function(){
return connectionPool.getConnectionAsync().disposer(
function(connection){return connection.release();}
);
};
var query = function(command){
return using(getConnection(), function(connection)
{
return connection.queryAsync(command);
});
};
app.use(bodyParser.json()); //for parsing application/json
// Attempts to resolve all get requests by reading from /public before
// trying other routes
app.use(express.static(__dirname + '/public'));
// ---------------------------------------------------------------------
// The desired behaviours of the following routes is described in api.md
// ---------------------------------------------------------------------
var archiveTransaction = function(voided) {
return query(mysql.format("INSERT INTO ??.transactions_archive (voided, user, first_timestamp, last_timestamp) values(?, ?, (SELECT min(timestamp) from ??.transaction_time), (SELECT max(timestamp) from ??.transaction_time))", [databaseName, voided, currentUser, databaseName, databaseName]))
.then(function(result){
tid = result.insertId; // TODO: this is global
return query(mysql.format("SELECT * FROM ??.current_transaction_view", databaseName));
})
.then(function(results){
results = results.map(function(row){
return "(" + tid + ", " + mysql.escape(row.item) + ", " + row.count + ", " + (row.price * row.count) + ")";
});
var resultString = results.join(",");
return query(mysql.format("INSERT INTO ??.transaction_items_archive (tid, item, count, subtotal) values" + resultString, databaseName));
})
.then(function(){
return query(mysql.format("TRUNCATE ??.transaction", databaseName));
})
.then(function(){
return query(mysql.format("TRUNCATE ??.transaction_time", databaseName));
});
}
app.get("/buttons",function(req,res){
var sql = mysql.format('SELECT buttonID,`left`,top,width,invID,item AS label FROM ??.till_buttons,??.inventory WHERE invID = id', [databaseName,databaseName]);
query(sql).then(function(rows){
res.send(rows);
}).catch(function(err){
console.log("Error in 'GET /buttons':");
console.log(err);
res.sendStatus(500);
});
});
app.get("/transaction" , function(req,res) {
query("SELECT itemId,count(itemId) AS count,price, item FROM "+databaseName+ ".transaction," +databaseName+ ".prices," +databaseName+ ".inventory"+
" WHERE prices.id=itemId AND itemId=inventory.id GROUP BY itemId;").then(function(rows) {
res.send(rows);
}).catch(function(err){
console.log("Error in 'GET /transaction':");
console.log(err);
res.sendStatus(500);
});
});
app.delete("/transaction/:itemId", function(req, res){
var itemId = req.params.itemId;
query(mysql.format("DELETE FROM ??.transaction WHERE itemId = ?", [databaseName, itemId])).then(function(result){
if(result.affectedRows == 0) {
res.sendStatus(404); // Can't delete nonexistent items
} else {
query(mysql.format("INSERT INTO ??.transaction_time (timestamp,action) VALUES (CURRENT_TIME() , 'deleted')", databaseName))
.then(function(result) {
res.send('');
});
}
}).catch(function(err){
console.log("Error in 'DELETE /transaction/:itemId':");
console.log(err);
res.sendStatus(500);
});
});
app.delete("/transaction" , function(req, res) {
archiveTransaction(true)
.then(function() {
res.send({"tid":tid});
}).catch(function(err){
console.log("Error in 'DELETE /transaction':");
console.log(err);
res.sendStatus(500);
});
});
app.post("/transaction", function(req,res) {
if (req.body["action"] == "commit sale") {
// TODO: we don't actually reduce the counts in `inventory` when selling items
archiveTransaction(false)
.then(function(){
res.send({"tid":tid});
}).catch(function(err){
console.log("Error in 'POST /transaction':");
console.log(err);
res.sendStatus(500);
});
} else {
res.sendStatus(400);
}
});
app.post("/transaction/:itemId" , function(req,res) {
var itemId = req.params.itemId;
query(mysql.format("INSERT INTO ??.transaction value(?)", [databaseName, itemId]))
.then(function(result) {
query(mysql.format("INSERT INTO ??.transaction_time (timestamp,action) VALUES (CURRENT_TIME() , 'clicked')", databaseName))
.then(function(result) {
res.send('');
});
}).catch(function(err){
console.log("Error in 'POST /transaction/:itemId':");
if(err.code == 'ER_NO_REFERENCED_ROW_2'){
console.log("Invalid Item ID");
res.status(400).send('Invalid Item ID');
} else {
console.log(err);
res.sendStatus(500);
}
});
});
app.post("/login", function(req,res) {
if((req.body["username"] !== undefined) && (req.body["password"] !== undefined)){
// check that this user is authorized
query(mysql.format("SELECT * FROM ??.till_users where username = ? AND password = ?", [databaseName, req.body["username"], req.body["password"]]))
.then(function(users){
if(users.length !== 0){
currentUser = req.body["username"];
res.send('');
} else {
res.sendStatus(403);
}
});
} else {
res.sendStatus(400);
}
});
app.post("/logout", function(req,res) {
currentUser = '';
res.sendStatus(204);
});
app.listen(port);