2011-06-13 11:23:02 +08:00
|
|
|
var app = require('express').createServer()
|
|
|
|
, Step = require(global.settings.app_root + '/lib/step')
|
|
|
|
, oAuth = require(global.settings.app_root + '/app/models/oauth')
|
|
|
|
, PSQL = require(global.settings.app_root + '/app/models/psql')
|
|
|
|
, _ = require('underscore');
|
|
|
|
_.mixin(require('underscore.string'));
|
|
|
|
|
|
|
|
|
|
|
|
// CartoDB v1 SQL API
|
|
|
|
//
|
|
|
|
// all requests expect the following URL args:
|
|
|
|
// - `sql` {String} SQL to execute
|
|
|
|
//
|
|
|
|
// for private (read/write) queries:
|
|
|
|
// - `auth_token` {String} oAuth API token from CartoDB. In URL or request header.
|
|
|
|
//
|
|
|
|
// eg. /v1/?sql=SELECT 1 as one&auth_token=my_token
|
|
|
|
//
|
|
|
|
// for public (read only) queries:
|
|
|
|
// - `database` {String} The database to execute queries on
|
|
|
|
//
|
|
|
|
// eg. /v1/?sql=SELECT 1 as one&database=my_public_db
|
|
|
|
//
|
|
|
|
// NOTE: private queries can only be ran on databases the oAuth key gives access to.
|
|
|
|
app.get('/v1/', function(req, res){
|
|
|
|
|
|
|
|
//sanitize input
|
2011-06-13 20:07:21 +08:00
|
|
|
var sql = req.query.sql;
|
|
|
|
var database = req.query.database;
|
2011-06-13 11:23:02 +08:00
|
|
|
sql = (sql == "") ? null : sql;
|
2011-06-13 20:07:21 +08:00
|
|
|
database = (database == "") ? null : database;
|
|
|
|
|
2011-06-13 11:23:02 +08:00
|
|
|
try {
|
|
|
|
if (!_.isString(sql)) throw new Error("You must indicate a sql query");
|
|
|
|
var pg;
|
|
|
|
|
|
|
|
Step(
|
|
|
|
function getUser() {
|
|
|
|
oAuth.authorize(req, this);
|
|
|
|
},
|
|
|
|
function querySql(err, user_id){
|
|
|
|
if (err) throw err;
|
|
|
|
pg = new PSQL(user_id, database);
|
|
|
|
pg.query(sql, this);
|
|
|
|
},
|
|
|
|
function packageResults(err, result){
|
|
|
|
if (err) throw err;
|
2011-06-16 17:55:36 +08:00
|
|
|
//pg.end(); //TODO: Fix this - we should use a proper generic pool
|
2011-06-13 11:23:02 +08:00
|
|
|
res.send(result.rows);
|
|
|
|
},
|
|
|
|
function exceptionHandle(err, result){
|
2011-06-13 20:07:21 +08:00
|
|
|
handleException(res,err);
|
2011-06-13 11:23:02 +08:00
|
|
|
}
|
|
|
|
);
|
|
|
|
} catch (err) {
|
2011-06-13 20:07:21 +08:00
|
|
|
handleException(res,err);
|
2011-06-13 11:23:02 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2011-06-13 20:07:21 +08:00
|
|
|
function handleException(res, err){
|
|
|
|
var msg = (global.settings.environment == 'development') ? {error:[err.message], stack: err.stack} : {error:[err.message]}
|
|
|
|
res.send(msg, 400);
|
|
|
|
}
|
|
|
|
|
2011-06-13 11:23:02 +08:00
|
|
|
app.listen(global.settings.node_port);
|
|
|
|
//module.exports = app;
|