Skip to content

Instantly share code, notes, and snippets.

@gartmeier
Last active May 1, 2019 13:08
Show Gist options
  • Save gartmeier/9186b76dd295e659d6c2b7c7d2043216 to your computer and use it in GitHub Desktop.
Save gartmeier/9186b76dd295e659d6c2b7c7d2043216 to your computer and use it in GitHub Desktop.
(function ($) {
var isWin = typeof Ti.App.Platform !== 'undefined'
&& Ti.App.Platform === 'Win';
var currentResourceId = 0,
deferredMap = {};
$.query = function (query, db) {
var id = nextQueryId(),
d = deferredMap[id] = $.Deferred(),
db = typeof db === 'undefined' ? $.query.defaults.db : db;
Ti.App.fireEvent('dbFunction', {
db: db,
pType: 'query',
source: $.query.defaults.source,
qID: id,
query: query,
callBack: 'onDbFunctionCallBack',
errorFunc: 'onDbFunctionError'
});
return d;
};
$.query.defaults = {
db: 'pitcher',
source: 'modal'
};
function nextQueryId() {
return ++currentResourceId;
}
window.onDbFunctionCallBack = function (json) {
var result = JSON.parse(json);
if (result === null
|| typeof result.qID === 'undefined'
|| typeof result.columns !== 'object'
|| typeof result.results !== 'object') {
throw new Error('Invalid parameter');
}
var d = deferredMap[result.qID];
if (typeof d === 'undefined') {
throw new Error('Deferred not found');
}
if (typeof result.error !== 'undefined') {
d.reject(result.error);
return;
}
if(isWin) {
d.resolve(result.results);
return;
}
var objects = [];
for (var i = result.results.length - 1; i >= 0; i--) {
var row = result.results[i],
obj = {};
for (var j = 0; j < result.columns.length; j++) {
var column = result.columns[j];
obj[column] = row[j];
}
objects.push(obj);
result.results.splice(i, 1);
}
d.resolve(objects.reverse());
};
window.onDbFunctionError = function (message) {
if (!message) {
message = 'Unknown Error';
}
throw new Error(message);
};
})(jQuery);
@gartmeier
Copy link
Author

Example: $.query('select * from tbl_crm_accounts_m_v3').done(function (accounts) { }).fail(function (error) {});

@gartmeier
Copy link
Author

gartmeier commented Oct 17, 2017

Set defaults : $.query.defaults.db = 'exemplum'; $.query.defaults.source = 'sfdcWebView';

@gartmeier
Copy link
Author

Chained example: $.when($.query('select * from bananas'), $.query('select * from oranges' )).done(function ( bananas, oranges ) {});

@gartmeier
Copy link
Author

Added Windows compability

@gartmeier
Copy link
Author

gartmeier commented Mar 24, 2018

define default database with $.query.defaults.db = 'pitcher' or pass it as function parameter $.query('select * from oranges', 'fruit')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment