Title / Description
Code /*! * Datapel apiConnect Library v1.2.0 (http://api.datapel.net) * Copyright 2011-2016 Datapel Systems Pty Ltd. * Licensed under MIT */ if (typeof jQuery === 'undefined') { throw new Error('Datapel API Connection JavaScript requires jQuery') } /* ======================================================================== * apiConnect: apiConnect.js v1.2.0 * http://api.datapel.net/samplecode * ======================================================================== * Copyright 2011-2016 Datapel Systems Pty Ltd. * * Example Usage: * ======================================================================== * apiConnect.username = "username"; * apiConnect.password = "password"; * apiConnect.url = "http://url:port"; * * ======================================================================== */ var apiConnect = new function () { // Define Connection Properties this.masterKey = ""; this.username = ""; this.password = ""; this.url = ""; this.token = ""; this.recordCount = 0; this.pageCount = 0; this.pageNumber = 0; this.pageSize = 0; this.pageStartTime = 0; this.pageEndTime = 0; this.pagePrimaryKeyName = ""; this.pageTableName = ""; this.pageQueryFilter = ""; this.pageColumns = ""; this.pageTag = ""; this.pageElapseTime = 0; this.pageResultSet = []; this.requestResultSet = []; this.requestEstimatedTime = 0; this.onPageComplete = function(){}; this.onPageException = function(){}; this.onRequestReady = function(){}; this.onRequestComplete = function(){}; this.localscope = {}; // ======================================================================== // openService(); // this.openService = function (callback) { // allow cross domain access $.support.cors = true; // Initialise the token this.token = ""; // Encode authorisation credentials this.masterKey = this.encode64(this.username + ':' + this.password); // Request API session token console.log(this.masterKey); // trigger the caller }; // ======================================================================== // getRequest() // this.getRequest = function (apiResource, apiFilter, callback) { var urlResponse; // form the request based on the resource var urlRequest = this.url + "/json/" + apiResource + "?filter~" + encodeURI(apiFilter); // append security credentials urlRequest = urlRequest + '&authorization=' + this.masterKey // pass request to server console.log("requesting: " + urlRequest); // allow cross domain by default $.support.cors = true; // Make request $.ajax({ // pass the resource request url: urlRequest, type: 'GET', crossDomain: true, async: true, success: function(result) { // completed request callback(result); }, error: function() { //failed result callback(false); } }); }; // ======================================================================== // getTimeStamp() // this.getTimeStamp = function (callback) { var urlResponse; // form the request based on the resource var urlRequest = this.url + "/json/timestamp?filter~"; // append security credentials urlRequest = urlRequest + '&authorization=' + this.masterKey // pass request to server console.log("requesting: " + urlRequest); // allow cross domain by default $.support.cors = true; // Make request $.ajax({ // pass the resource request url: urlRequest, type: 'GET', crossDomain: true, async: true, success: function(result) { // check response is valid if(result!=null && result !=undefined) { //successful result callback(result.ServerTimeStamp); } else { //invalid result callback(false); } }, error: function() { //failed result callback(false); } }); }; // ======================================================================== // getDataSetPage() // this.getDataSetPage = function (tableName, tableColumns, tableFilter, tablePkey, pageSize, pageNumber) { var queryString = ""; try { // All Rows or filtered dataSet if (!tableFilter.trim()) { // is empty or whitespace tableFilter = "1=1"; } // All Columns or subSet if (!tableColumns.trim()) { // is empty or whitespace tableColumns = "*"; } // create the page query with filter queryString = "SELECT " + tableColumns + " FROM " + tableName + " WHERE " + tableFilter + " AND " + tablePkey + " IN "; queryString = queryString + "(SELECT TOP " + pageSize + " " + tablePkey + " FROM " + tableName + " WHERE " + tableFilter + " AND " + tablePkey + " NOT IN "; queryString = queryString + "(SELECT TOP " + pageSize*(pageNumber-1) + " " + tablePkey + " FROM " + tableName + " WHERE " + tableFilter + " ORDER BY " + tablePkey + ")"; queryString = queryString + " ORDER BY " + tablePkey + ")" + " ORDER BY " + tablePkey; // echo the query for debug console.log("Page Query:" + queryString); //debugger; } catch (ex) { alert("getDataset: Failed!"); console.log("Error:" + ex.message); queryString = ""; } // Return the page query return(queryString); }; // ======================================================================== // getPagedRequest() // this.getPagedRequest = function (tableFilter, onPageComplete, onPageException, onRequestReady, onRequestComplete) { // New QueryString var queryRequest = ""; var self = this; // Initialise context self.pageQueryFilter = tableFilter; // Initialise Event callbacks self.onPageComplete = onPageComplete; self.onPageException = onPageException; self.onRequestReady = onRequestReady; self.onRequestComplete = onRequestComplete; self.pageResultSet = []; self.requestResultSet = []; // Determine the number of records in the dataSet setTimeout(function() { // From Table get RecordCount queryRequest = "SELECT COUNT(*) AS recordCount FROM " + self.pageTableName + " WHERE " + self.pageQueryFilter; apiConnect.getRequest("sql", queryRequest, apiConnect.pagedRequestBegin); }, 3000); }; // ======================================================================== // pagedRequestBegin() // this.pagedRequestBegin = function (resultSet) { var queryRequest = ""; var recordCount = 0; var pagesCount = 1; var self = apiConnect; // Echo resultSet to console if (resultSet) { console.log("Items Loaded :" + JSON.stringify(resultSet)); } else { console.log("No results."); } // Validate the previous resultSet if (resultSet) { console.log("Records Loaded :" + JSON.stringify(resultSet)); recordCount = parseInt(resultSet[0].recordCount); if (recordCount > 0) { pagesCount = Math.ceil(recordCount / self.pageSize); } } else { console.log("No results."); } // Initialise the apiConnect with pageCount self.pageCount = pagesCount; // initiate the event callback self.onRequestReady('onRequestReady'); // fire Request("sql-request", filter-select query, callback) setTimeout(function() { // Complete Request self.pageNumber = 1; queryRequest = self.getDataSetPage(self.pageTableName, self.pageColumns, self.pageQueryFilter, self.pagePrimaryKeyName, self.pageSize, self.pageNumber); if (queryRequest.trim()) { self.pageStartTime = performance.now(); self.getRequest("sql", queryRequest, self.pagedRequestNext); } else { console.log("Server Connection Failed: (Invalid DataSet)"); } }, 3000); }; // ======================================================================== // pagedRequestNext() // this.pagedRequestNext = function (resultSet) { // New QueryString var queryRequest = ""; var self = apiConnect; // Mark Page Loaded self.pageEndTime = performance.now(); self.pageElapseTime = self.pageEndTime - self.pageStartTime; self.requestEstimatedTime = self.pageElapseTime * self.pageCount; // Echo resultSet to console if (resultSet) { self.pageResultSet = resultSet; self.requestResultSet = self.requestResultSet.concat(resultSet); console.log("pageResultSet :" + JSON.stringify(resultSet)); } else { console.log("No results."); } // initiate the event callback self.onPageComplete('onPageComplete'); // Page Download Complete - step to next page self.pageNumber = self.pageNumber + 1; // fire page Request with filter-select query, then callback setTimeout(function() { // Complete Request self.pageStartTime = performance.now(); queryRequest = self.getDataSetPage(self.pageTableName, self.pageColumns, self.pageQueryFilter, self.pagePrimaryKeyName, self.pageSize, self.pageNumber); if (queryRequest.trim()) { if (self.pageNumber != self.pageCount) { // Download next page in Request Set self.getRequest("sql", queryRequest, self.pagedRequestNext); } else { // Final page download in Request Set self.getRequest("sql", queryRequest, self.pagedRequestComplete); } } else { console.log("Server Connection Failed: (Invalid DataSet)"); } }, 3000); }; // ======================================================================== // pagedRequestComplete() // this.pagedRequestComplete = function (resultSet) { try { var self = apiConnect; if (resultSet) { self.pageResultSet = resultSet; self.requestResultSet = self.requestResultSet.concat(resultSet); console.log("requestResultSet :" + JSON.stringify(self.requestResultSet)); } else { console.log("No results."); } // initiate the event callback self.onRequestComplete('onRequestComplete'); console.log("Request COMPLETE!"); } catch (ex) { alert("Failed!"); console.log("Error:" + ex.message); } }; // Use this function to encode64 ONLY FOR APIKEY this.encode64 = function (input) { var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; }; };
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code