forked from timwis/soda-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (52 loc) · 1.91 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
var request = require('request');
var parser = require('node-tims-custom-soql-parser'),
restify = require('restify'),
_ = require('underscore'),
anyDB = require('any-db-postgres'),
processWhere = require('./lib/where'),
processSelect = require('./lib/select');
require('dotenv').load({silent: true});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 5000,
server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1',
tables = {},
server = restify.createServer();
server.use(restify.queryParser());
server.get('/:user/:table', function(req, res, next) {
// If table doesn't exist, send error
if (!req.query) {
req.query = '';
}
// Parse query into AST
var ast = parser.parse(req.query);
// Process SELECT columns
//ast.columns = processSelect(ast.columns, tables[req.params.table]);
// Add FROM table to AST
ast.from = [{table: '"' + req.params.table + '"'}];
// Process WHERE recursively
if(ast.where) ast.where = processWhere(ast.where);
// Convert AST back to SQL
var sql = parser.stringify.parse(ast);
if (req.params.table == 'tables') {
sql = sql.replace('FROM "tables"', "FROM (SELECT CDB_UserTables('all')) tables");
}
var url = 'https://'+req.params.user+'.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql);
console.log(url);
console.log(sql);
request(url, function (error, response, body) {
console.log(body);
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
data['sql'] = sql;
res.json(data);
next();
} else {
res.json(JSON.parse(body));
next();
}
})
});
var server_port = process.env.YOUR_PORT || process.env.PORT || 8080;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
console.log('%s listening at %s', server.name, server.url);
});