As covered in Handler for cScriptDbCom requests, a handler will deal with REST requests from VBA API for scriptDB.
In addition to a reference to the dispatcher library, it needs a reference to a GAS LIbrary for the appropriate class, which can be found at resource
ML7nE0jnmV4tCqTYKNkIykai_d-phDA33,
and typically will be constructed like this.
1 |
var c = new scriptDbCom.cScriptDbCom ( e,scriptDbDispatch.getDb(e.parameter.library),whatsAllowed); |
Page Content
hide
scriptDbCom handler
The Code
ML7nE0jnmV4tCqTYKNkIykai_d-phDA33
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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
/** * create a cScriptDbCom instance * @param {object} e arguments passed to the web app * @param {ScriptDBInstance} repoDb the scriptDB to operate on * @param {[String]} allowedOperations list of operations that can be done. default ['delete','create','update','query','count','getbyid'] * return {cScriptDbCom} a new cScriptDbCom object */ function cScriptDbCom (e,repoDb,allowedOperations) { var debugLogger = null; var HANDLERAPI = 'GASv0102'; var QUERYLIMIT = 50; var self = this; var pdb = repoDb; var pResult; var pBatch = {method:null, queue:[], status:'good'}; var pAllowed = allowedOperations || ['delete','create','update','query','count','getbyid']; /** * return results of latest request * return {object} latest request result */ self.getResult = function() { return pResult; } /** * @param {object} e arguments passed to the web app * return {object} defaults added to given parameters */ self.argDefaults = function (e) { e = e || {}; e.parameter = e.parameter || {}; e.parameter.class = e.parameter.class || "xLiberation"; e.parameter.debug = e.parameter.hasOwnProperty("debug") ? e.parameter.debug : 1; e.parameter.clientApi = e.parameter.api || 'unknown'; return e; } //set up the defaults var eArgs = self.argDefaults(e); /** * return {object} the latest args, including the defaults */ self.getArgs = function () { return eArgs; } self.getParam = function(prop) { return self.getArgs().parameter[prop]; } self.isAllowed = function(access) { // check if something is allowed or not if (pAllowed.indexOf(access) > -1) { return true; } else { pResult.status ='bad'; pResult.error = access + " operation not allowed on this db"; return false; } } /** * return {object} the latest results, following a query request */ self.handleQuery = function () { // the query here will return only up to the Limit. If you need more, you need to manage calls using skip & limit // setup the query, adding the silo for this class pResult = {status:'good',count:0,results:[]}; var e = this.getArgs(); var q = this.querySet( e.parameter.where ? JSON.parse(e.parameter.where) : null ); if (e.parameter.count) { // this is a simple count pResult.handler = "count"; if (self.isAllowed(pResult.handler)) { pResult.count=pdb.count(q); } } else if (e.parameter.objectid) { pResult.handler = "getbyid"; if (self.isAllowed(pResult.handler)) { // get by its object ID var record = pdb.load(e.parameter.objectid); if (record) { pResult.count = 1; record.objectId = record.getId(); delete record.siloId; pResult.results= [record] ; } else { pResult.status = 'bad'; pResult.error = 'Could not find object with id:' + e.parameter.objectid; } } } else { pResult.handler = "query"; if (self.isAllowed(pResult.handler)) { var dbResult = pdb.query (q) .limit(e.parameter.hasOwnProperty("limit") ? e.parameter.limit : QUERYLIMIT) .startAt(e.parameter.skip || 0 ); // setup convenience count var results = []; pResult.count = dbResult.getSize(); // return the results while (dbResult.hasNext()) { var o = dbResult.next(); o.objectId = o.getId(); delete o.siloId; results.push(o); } pResult.results = results; } } return pResult; } /** * find the requested object by its object ID in the queue of things in a batch. All Posts are batched. * @param {String} id arguments passed to the web app * return {Object} the batch queue item */ self.findInQueue = function (id) { for (var i=0; i < pBatch.queue.length ; i++) { if (pBatch.queue[i].objectId === id) return pBatch.queue[i]; } return null; } self.getIds = function () { var ids = []; for (var i =0; i <pBatch.queue.length; i++) { var id = pBatch.queue[i].objectId; if (!id) { pResult = {status:'bad', error: 'missing objectID from batched post request',results:{}}; return null; } ids.push(id); } return ids; } /** * record access - note that per policy, silo will expire , and message will be deleted 24 hours after creation */ self.getStamps = function (record) { if (!record.stamps) record.stamps = {}; return record.stamps; }; self.stamp = function (record,prop) { var s = self.getStamps(record); s[prop] = new Date().getTime(); s.api = self.getParam('clientApi'); s.handler = HANDLERAPI; return self; }; /** * since we are using batching, this would flush out the queued request * return {Object} the flush result */ self.flush = function() { var results; pResult = {status:'good',results:[],handler:"flush"}; function breakingBad (resultObject,theError,theResults) { resultObject.error = theError; resultObject.results = theResults; resultObject.status = 'bad'; return resultObject; } // the method selects the activity if (pBatch.queue.length ) { if (pBatch.method === 'POST') { // this is a create - simply save the result try { pBatch.queue.forEach( function (rec) { self.stamp(rec,"created")}); results = pdb.saveBatch(pBatch.queue,false); } catch(err) { return breakingBad (pResult, err, results); } } else if (pBatch.method === 'PUT') { // we can get the current values by objectId var ids = self.getIds(); if (!ids) return pResult; try { var records = pdb.load (ids); } catch(err) { return breakingBad (pResult, err, records); } // did we get any? if(records) { try { // go through what we got var targetId; for (var i = 0; i < records.length; i++ ) { targetId=records[i].getId(); // find this object in the batch update list var q = self.findInQueue (targetId); if (q) { for ( var k in q) { records[i][k] = q[k]; } if (records[i].hasOwnProperty("objectId")) { delete records[i].objectId; } self.stamp(records[i],"updated"); } } } catch (err) { return breakingBad (pResult, 'trying to get objectId for postData:' + err + 'id-' + targetId, records); } // now save all these changes as a batch try { results = pdb.saveBatch (records,false); if (!pdb.allOk(results)) { return breakingBad (pResult, "Batch save failure" , results); } } catch(err){ return breakingBad (pResult , err, records); } } } else if (pBatch.method === 'DELETE') { var ids = self.getIds(); if (!ids) return pResult; // delete is pretty straightforward by ID try { results = pdb.removeByIdBatch(ids, false); } catch(err){ return breakingBad (pResult , 'error removing from batches:'+err , results); } } else { return breakingBad (pResult , 'unknown method in batch operation:' + pBatch.method , []); } if (!pdb.allOk(results)) { return breakingBad (pResult , "Failed to complete all batch operations" , []) } else { pBatch.queue = []; } } return pResult; } /** * handle a post request from the app * return {Object} the flush result */ self.handlePost = function() { var p = self.getPostData(); if (!p) { pResult = {status:'bad', error:'no postdata provided in post request', results:[], count:0}; return pResult; } pResult = {status:'good',count:p.requests.length,results:[],postData:p}; // posts are always batched up, and follow the same form as parse.com API // {requests:[ {body:{},path:class,method:'POST'(create)|'PUT'(update)|'DELETE'(delete)},...] for ( var i = 0; i < p.requests.length ; i++ ) { var method = p.requests[i].method; pResult.handler = method; if (pBatch.method != method) { if (self.flush().status !='good') return pResult; } if (self.isAllowed( method === "POST" ? 'create' : (method === "DELETE" ? 'delete' :(method === "PUT" ? 'update':method)))) { pBatch.queue.push(self.querySet(p.requests[i].body,p.requests[i].path)); pBatch.method = method; } else { return pResult; } } return self.flush(); } /** * get the data the web app posted * return {Object} the post Data */ self.getPostData = function () { var data; // this is when a post is not possible, and the post data has been sent as an argument if (eArgs.parameter.postdata) { data = JSON.parse(e.parameter.postdata); } else { data = (e.postData && e.postData.contents) ? JSON.parse(e.postData.contents) : null; } return data; } /** * get the class that applies to the this instance * return {String} the class */ self.getClass = function () { return eArgs.parameter.class ; } /** * get the request type * return {String} the class */ self.getRequestType = function () { return eArgs.parameter.method || eArgs.requestType ; } /** * merge the query object, with the silo that this class is held in * return {Object} the query we need to make */ self.querySet = function (ob,optClass) { var ob = ob || {}; ob.siloId = optClass || this.getClass(); return ob; } /** * handle the web apps request * return {Object} the query we need to make */ self.requestResult = function () { if (this.getRequestType() === "POST") { this.handlePost(); } else if (this.getRequestType()=== "GET") { this.handleQuery(); } if (this.getArgs().debug) { pResult.debug = eArgs; } return pResult; } } function makeContent(e,type,allowed,dispatcher) { e.requestType = type; var c = new cScriptDbCom ( e,dispatcher,allowed); var content = JSON.stringify(c.requestResult()); return e.parameter.callback ? e.parameter.callback + "(" + content + ");" : content; } |
You can get me on Twitter or this forum, and compare this topic with parse.com – nosql database for VBA and parse.com – noSQL database for GAS so you can see more about choosing about which noSQL database to use.
For help and more information join our forum, follow the blog or follow me on Twitter