Skip to content

Commit

Permalink
add query module
Browse files Browse the repository at this point in the history
  • Loading branch information
xjsender committed Mar 25, 2015
1 parent 990bc52 commit 114924e
Show file tree
Hide file tree
Showing 13 changed files with 386 additions and 76 deletions.
17 changes: 16 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,27 @@ app.use(bodyParser.urlencoded({
extended: true
}));

// expose the "messages" local variable when views are rendered
app.use(function(req, res, next) {
var msgs = req.session.messages || [];

// expose "messages" local variable
res.locals.message = msgs;

// expose "hasMessages"
res.locals.hasMessage = !!msgs.length;

// res.locals.user = req.session.user;

next();
});

// app.use('/', webRouter);
webRouter(app);
app.use(router);

var server = app.listen(process.env.PORT || 3000, function() {
var host = server.address().address
var port = server.address().port
console.log('Example Node Tree listening at http://%s:%s', host, port)
console.log('Node Tree listening at http://%s:%s', host, port)
})
4 changes: 2 additions & 2 deletions config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var config = {
"redirect_uri": "https://node-jstree.herokuapp.com/oauth/callback"
// "redirect_uri": "https://locahost:3000/oauth/callback"
// "redirect_uri": "https://node-jstree.herokuapp.com/oauth/callback"
"redirect_uri": "http://localhost:3000/oauth/callback"
};

module.exports = config;
47 changes: 47 additions & 0 deletions controller/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
var jsforce = require("jsforce")
, session = require("express-session")
, config = require("../config");

exports.login = function(req, res, next) {
req.session.oauth2 = {
loginUrl: req.body.login_url,
clientId: req.body.client_id,
clientSecret: req.body.client_secret,
redirectUri: config.redirect_uri
}

oauth2 = new jsforce.OAuth2(req.session.oauth2)
authorize_url = oauth2.getAuthorizationUrl({scope: 'full'});
res.redirect(authorize_url);
}

exports.logout = function(req, res, next) {
req.session.destroy(function() {
res.locals.session.destroy();
res.redirect('/');
});
}

exports.callback = function(req, res, next) {
var conn = new jsforce.Connection({
oauth2: req.session.oauth2
});

var code = req.query.code;
conn.authorize(code, function(err, userInfo) {
if (err) { return console.error(err); }

req.session.accessToken = conn.accessToken;
req.session.instanceUrl = conn.instanceUrl;
req.session.userId = conn.userInfo.id;

soql = "SELECT UserName FROM User WHERE Id = '{0}'".format(req.session.userId);
conn.query(soql , function(err, resp) {
if (err) return next(err);

req.session.userName = resp.records[0].Username;

res.redirect("/");
});
});
}
File renamed without changes.
71 changes: 30 additions & 41 deletions controller/site.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,40 @@
var jsforce = require("jsforce")
, session = require("express-session")
, config = require("../config")
, _ = require("underscore")._
, array2table = require("../lib/array2table");

exports.index = function(req, res, next) {
res.render('index');
}
if (req.session.accessToken) {
var conn = new jsforce.Connection({
accessToken: req.session.accessToken,
instanceUrl: req.session.instanceUrl
});

exports.about = function(req, res, next) {
res.render('about');
}
soql = "SELECT UserName FROM User WHERE Id = '{0}'".format(req.session.userId);
conn.query(soql , function(err, resp) {
if (err) return next(err);

exports.login = function(req, res, next) {
req.session.oauth2 = {
loginUrl: req.body.login_url,
clientId: req.body.client_id,
clientSecret: req.body.client_secret,
redirectUri: config.redirect_uri
req.session.userName = resp.records[0].Username;
res.locals.session = req.session;
});
}

console.log(req.session.oauth2);

oauth2 = new jsforce.OAuth2(req.session.oauth2)
res.redirect(oauth2.getAuthorizationUrl({scope: 'api'}));
}

exports.logout = function(req, res, next) {
req.session.destroy(function() {
res.locals.session.destroy();
console.log(res.locals.session);
res.redirect('/');
});
console.log(req.session);
res.render('index');
}

exports.callback = function(req, res, next) {
var conn = new jsforce.Connection({
oauth2: req.session.oauth2
});

var code = req.query.code;
conn.authorize(code, function(err, userInfo) {
if (err) { return console.error(err); }

req.session.accessToken = conn.accessToken;
req.session.instanceUrl = conn.instanceUrl;
res.redirect('/');
});
exports.about = function(req, res, next) {
res.render('about');
}

exports.query = function(req, res, next) {
res.render("query", {
records: []
html_table: []
});
}

exports.doQuery = function(req, res, next) {
var soql = req.query.soql;
var soql = req.body.soql;

if (!req.session || !req.session.accessToken) {
return res.redirect('/');
Expand All @@ -66,10 +46,19 @@ exports.doQuery = function(req, res, next) {
});

conn.query(soql, function(err, resp) {
if (err) return next(err);
if (err) {
res.locals.hasMessage = true;
res.locals.messages = err;

res.render("query", {
html_table: ""
})
}

html_table = array2table(resp.records, 'queryResult', 'table', req.session);

res.render("query", {
records: resp.records
html_table: html_table
});
});
}
189 changes: 189 additions & 0 deletions lib/array2table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/**
* JavaScript format string function
*
*/
String.prototype.format = function() {
var args = arguments;

return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] :
'{' + number + '}';
});
};


/**
* Convert a Javascript Oject array or String array to an HTML table
* JSON parsing has to be made before function call
* It allows use of other JSON parsing methods like jQuery.parseJSON
* http(s)://, ftp://, file:// and javascript:; links are automatically computed
*
* JSON data samples that should be parsed and then can be converted to an HTML table
* var objectArray = '[{"Total":"34","Version":"1.0.4","Office":"New York"},{"Total":"67","Version":"1.1.0","Office":"Paris"}]';
* var stringArray = '["New York","Berlin","Paris","Marrakech","Moscow"]';
* var nestedTable = '[{ key1: "val1", key2: "val2", key3: { tableId: "tblIdNested1", tableClassName: "clsNested", linkText: "Download", data: [{ subkey1: "subval1", subkey2: "subval2", subkey3: "subval3" }] } }]';
*
* Code sample to create a HTML table Javascript String
* var jsonHtmlTable = ConvertJsonToTable(eval(dataString), 'jsonTable', null, 'Download');
*
* Code sample explaned
* - eval is used to parse a JSON dataString
* - table HTML id attribute will be 'jsonTable'
* - table HTML class attribute will not be added
* - 'Download' text will be displayed instead of the link itself
*
* @author Afshin Mehrabani <afshin dot meh at gmail dot com>
*
* @class ConvertJsonToTable
*
* @method ConvertJsonToTable
*
* @param parsedJson object Parsed JSON data
* @param tableId string Optional table id
* @param tableClassName string Optional table css class name
* @param linkText string Optional text replacement for link pattern
*
* @return string Converted JSON to HTML table
*/
module.exports = function ConvertJsonToTable(parsedJson, tableId, tableClassName, options) {
//Patterns for links and NULL value
var italic = '<i>{0}</i>';
var link = '<a href="{0}/secur/frontdoor.jsp?sid={1}&retURL={2}" target="_blank">{2}</a>';

//Pattern for table
var idMarkup = tableId ? ' id="' + tableId + '"' : '';

var instance_url = options["instanceUrl"];
var session_id = options["accessToken"];

var classMarkup = tableClassName ? ' class="' + tableClassName + '"' : '';

var tbl = '<table ' + idMarkup + classMarkup + '>{0}{1}</table>';

//Patterns for table content
var th = '<thead>{0}</thead>';
var tb = '<tbody>{0}</tbody>';
var tr = '<tr>{0}</tr>';
var thRow = '<th>{0}</th>';
var tdRow = '<td>{0}</td>';
var thCon = '';
var tbCon = '';
var trCon = '';

if (parsedJson) {
var isStringArray = typeof(parsedJson[0]) == 'string';
var headers;

// Create table headers from JSON data
// If JSON data is a simple string array we create a single table header
if (isStringArray)
thCon += thRow.format('value');
else {
// If JSON data is an object array, headers are automatically computed
if (typeof(parsedJson[0]) == 'object') {
headers = array_keys(parsedJson[0]);

for (i = 0; i < headers.length; i++) {
thCon += thRow.format(headers[i]);
}
}
}
th = th.format(tr.format(thCon));

// Create table rows from Json data
if (isStringArray) {
for (i = 0; i < parsedJson.length; i++) {
tbCon += tdRow.format(parsedJson[i]);
trCon += tr.format(tbCon);
tbCon = '';
}
} else {
if (headers) {
var urlRegExp = new RegExp(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig);
var javascriptRegExp = new RegExp(/(^javascript:[\s\S]*;$)/ig);
var idRegExp = new RegExp(/[a-zA-Z0-9]{18}/ig);

for (i = 0; i < parsedJson.length; i++) {
for (j = 0; j < headers.length; j++) {
var value = parsedJson[i][headers[j]];
var isUrl = urlRegExp.test(value) || javascriptRegExp.test(value);
var isId = idRegExp.test(value);

if (isUrl) {
tbCon += tdRow.format(link.format(value));
}
else if (isId) {
tbCon += tdRow.format(link.format(instance_url, session_id, value));
}
else {
if (value) {
if (typeof(value) == 'object') {
//for supporting nested tables
tbCon += tdRow.format(ConvertJsonToTable(eval(value.data), value.tableId, value.tableClassName, value.linkText));
} else {
tbCon += tdRow.format(value);
}

} else { // If value == null we format it like PhpMyAdmin NULL values
tbCon += tdRow.format(italic.format(''));
}
}
}
trCon += tr.format(tbCon);
tbCon = '';
}
}
}
tb = tb.format(trCon);
tbl = tbl.format(th, tb);

return tbl;
}
return null;
}


/**
* Return just the keys from the input array, optionally only for the specified search_value
* version: 1109.2015
* discuss at: http://phpjs.org/functions/array_keys
* + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* + input by: Brett Zamir (http://brett-zamir.me)
* + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* + improved by: jd
* + improved by: Brett Zamir (http://brett-zamir.me)
* + input by: P
* + bugfixed by: Brett Zamir (http://brett-zamir.me)
* * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
* * returns 1: {0: 'firstname', 1: 'surname'}
*/
function array_keys(input, search_value, argStrict) {
var search = typeof search_value !== 'undefined',
tmp_arr = [],
strict = !!argStrict,
include = true,
key = '';

if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return input.keys(search_value, argStrict);
}

for (key in input) {
if (key === "attributes") continue; // SFDC Specified
if (input.hasOwnProperty(key)) {
include = true;
if (search) {
if (strict && input[key] !== search_value) {
include = false;
}
else if (input[key] != search_value) {
include = false;
}
}
if (include) {
tmp_arr[tmp_arr.length] = key;
}
}
}
return tmp_arr;
}
1 change: 0 additions & 1 deletion public/css/default.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,4 @@
#content {
color: #646464;
background-color: #fff;
padding: 30px 0;
}
Loading

0 comments on commit 114924e

Please sign in to comment.