Javascript Code example

Javascript code posted
created at 18 Apr 10:47

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*!
 * 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;
    };
};
13.1 KB in 12 ms with coderay