-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (86 loc) · 2.43 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
var express = require('express');
var bodyParser = require('body-parser');
var db = require('bluebird').promisifyAll(require('pg'));
var app = express();
var port = process.env.PORT || 5000;
var connection_url = process.env.DATABASE_URL || '';
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var operations = {
list: {
query: 'SELECT * FROM landscapes',
handler: listHandler,
},
add: {
query: 'INSERT INTO landscapes (name) VALUES ($1) ',
handler: operationHandler,
},
remove: {
query: 'DELETE FROM landscapes WHERE name = $1',
handler: operationHandler,
},
lock: {
query: 'UPDATE landscapes SET locked_by = $2 WHERE name = $1',
handler: operationHandler,
},
unlock: {
query: 'UPDATE landscapes SET locked_by = NULL WHERE name = $1',
handler: operationHandler,
}
};
function listHandler(result) {
if (!result.rows.length) {
return 'No landscapes found';
}
var list = "Landscapes:\n\n";
landscapes = result.rows;
for (var i = landscapes.length - 1; i >= 0; i--) {
var landscape = landscapes[i];
list += landscape.name + ': ' + (landscape.locked_by || 'unlocked') + "\n";
}
return list;
}
function operationHandler(result) {
if (result.rowCount) {
return 'Successful!';
}
return 'Something went wrong!';
}
app.post('/', urlencodedParser, function (req, res) {
// parsing `text` for args
var parsed = req.body.text.split(' '),
command = (!parsed || parsed.length < 2) ? 'list' : parsed[0],
input = '',
sql = '',
params = [];
// no command, no fun for you!
if (!operations[ command ]) {
return res.send('Action Unsupported');
}
// get query/handler from operations map
sql = operations[ command ].query;
handler = operations[ command ].handler;
// determine landscape and parameters if necessary
if (command !== 'list') {
landscape = parsed[1];
params.push(landscape);
if (command === 'lock') {
params.push(req.body.user_name);
}
}
// execute query and handler
db.connectAsync(connection_url).spread(function(connection, release) {
return connection.queryAsync(sql, params)
.then(handler)
.then(function(response_text) {
res.send(response_text);
})
.catch(function(e) {
res.send(e.name + ': ' + e.message);
})
.finally(function() {
release();
});
});
});
app.listen(port);
console.log( 'Running on' + port );