Last active
May 1, 2019 13:08
-
-
Save gartmeier/9186b76dd295e659d6c2b7c7d2043216 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
Set defaults : $.query.defaults.db = 'exemplum'; $.query.defaults.source = 'sfdcWebView';
Chained example: $.when($.query('select * from bananas'), $.query('select * from oranges' )).done(function ( bananas, oranges ) {});
Added Windows compability
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
Example:
$.query('select * from tbl_crm_accounts_m_v3').done(function (accounts) { }).fail(function (error) {});