]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/PermaCrud.js
Stopping the leak
[working/Evergreen.git] / Open-ILS / web / js / dojo / openils / PermaCrud.js
1 /* ---------------------------------------------------------------------------
2  * Copyright (C) 2008  Equinox Software, Inc
3  * Mike Rylander <miker@esilibrary.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * ---------------------------------------------------------------------------
15  */
16
17 if(!dojo._hasResource["openils.PermaCrud"]) {
18
19     dojo._hasResource["openils.PermaCrud"] = true;
20     dojo.provide("openils.PermaCrud");
21     dojo.require("fieldmapper.Fieldmapper");
22     dojo.require("openils.User");
23
24     dojo.declare('openils.PermaCrud', null, {
25
26         session : null,
27         authtoken : null,
28         connnected : false,
29         authoritative : false,
30
31         constructor : function ( kwargs ) {
32             kwargs = kwargs || {};
33
34             this.authtoken = kwargs.authtoken;
35             this.authoritative = kwargs.authoritative;
36
37             this.session =
38                 kwargs.session ||
39                 new OpenSRF.ClientSession('open-ils.pcrud');
40
41             if (
42                 this.session &&
43                 this.session.state == OSRF_APP_SESSION_CONNECTED
44             ) this.connected = true;
45         },
46
47         auth : function (token) {
48             if (token) this.authtoken = token;
49             return this.authtoken || openils.User.authtoken;
50         },
51
52         connect : function ( onerror ) {
53             if (!this.connected && !this.session.connect()) {
54                 this.connected = false;
55                 if (onerror) onerror(this.session);
56                 return false;
57             }
58             this.connected = true;
59             return true;
60         },
61
62         disconnect : function ( onerror ) {
63             this.connected = false;
64             return true;
65             // disconnect returns nothing, which is null, which is not true, cause the following to always run ... arg.
66             if (!this.session.disconnect()) {
67                 if (onerror) onerror(this.session);
68                 return false;
69             }
70         },
71
72         _session_request : function ( args /* hash */, commitOnComplete /* set to true, else no */ ) {
73
74             var me = this;
75             var endstyle = 'rollback';
76             if (commitOnComplete) endstyle = 'commit';
77
78             if (me.authoritative) {
79                 if (!me.connected) me.connect();
80                 if (args.timeout && !args.oncomplete && !args.onresponse) { // pure sync call
81                     args.oncomplete = function (r) {
82                         me.session.request('open-ils.pcrud.transaction.' + endstyle, me.auth());
83                         me.session.disconnect();
84                         me.disconnect();
85                     };
86                 } else if (args.oncomplete) { // there's an oncomplete, fire that, and then end the transaction
87                     var orig_oncomplete = args.oncomplete;
88                     args.oncomplete = function (r) {
89                         var ret;
90                         try {
91                             ret = orig_oncomplete(r);
92                         } finally {
93                             me.session.request('open-ils.pcrud.transaction.' + endstyle, me.auth());
94                             me.session.disconnect();
95                             me.disconnect();
96                         }
97                         return ret;
98                     };
99                 }
100
101             if (me.authoritative) me.session.request('open-ils.pcrud.transaction.begin', me.auth() );
102
103             return me.session.request( args );
104
105         },
106
107         retrieve : function ( fm_class /* Fieldmapper class hint */, id /* Fieldmapper object primary key value */,  opts /* Option hash */) {
108             if(!opts) opts = {};
109             var req_hash = dojo.mixin(
110                 opts, 
111                 { method : 'open-ils.pcrud.retrieve.' + fm_class,
112                   params : [ this.auth(), id ]
113                 }
114             );
115
116             if (!opts.async && !opts.timeout) req_hash.timeout = 10;
117
118             var _pcrud = this;
119             var req = this._session_request( req_hash );
120
121             if (!req.onerror)
122                 req.onerror = function (r) { throw js2JSON(r); };
123
124             // if it's an async call and the user does not care about 
125             // the responses, pull them off the network and discard them
126             if (!req_hash.timeout && !req.oncomplete)
127                 req.oncomplete = function (r) { while(r.recv()){}; };
128
129             req.send();
130
131             // for synchronous calls with no handlers, return the first received value
132             if (req_hash.timeout && !opts.oncomplete && !opts.onresponse) {
133                 var resp = req.recv();
134                 if(resp) return resp.content();
135                 return null;
136             }
137
138             return req;
139         },
140
141         retrieveAll : function ( fm_class /* Fieldmapper class hint */, opts /* Option hash */) {
142             var pkey = fieldmapper[fm_class].Identifier;
143
144             if(!opts) opts = {};
145             var order_by = {};
146             if (opts.order_by) order_by.order_by = opts.order_by;
147             if (opts.select) order_by.select = opts.select;
148             if (opts.limit) order_by.limit = opts.limit;
149             if (opts.offset) order_by.offset = opts.offset;
150             if (opts.join) order_by.join = opts.join;
151             
152             var method = 'open-ils.pcrud.search.' + fm_class;
153             if(!opts.streaming) method += '.atomic';
154
155             var search = {};
156             search[pkey] = { '!=' : null };
157
158             var req_hash = dojo.mixin(
159                 opts, 
160                 { method : method,
161                   params : [ this.auth(), search, order_by ]
162                 }
163             );
164
165             if (!opts.async && !opts.timeout) req_hash.timeout = 10;
166
167             var _pcrud = this;
168             var req = this._session_request( req_hash );
169
170             if (!req.onerror)
171                 req.onerror = function (r) { throw js2JSON(r); };
172             
173             // if it's an async call and the user does not care about 
174             // the responses, pull them off the network and discard them
175             if (!req_hash.timeout && !req.oncomplete)
176                 req.oncomplete = function (r) { while(r.recv()){}; };
177
178             req.send();
179
180             // for synchronous calls with no handlers, return the first received value
181             if (req_hash.timeout && !opts.oncomplete && !opts.onresponse) {
182                 var resp = req.recv();
183                 if(resp) return resp.content();
184                 return null;
185             }
186
187             return req;
188         },
189
190         search : function ( fm_class /* Fieldmapper class hint */, search /* Fieldmapper query object */, opts /* Option hash */) {
191             var return_type = 'search';
192             if(!opts) opts = {};
193             var order_by = {};
194             if (opts.order_by) order_by.order_by = opts.order_by;
195             if (opts.select) order_by.select = opts.select;
196             if (opts.limit) order_by.limit = opts.limit;
197             if (opts.offset) order_by.offset = opts.offset;
198             if (opts.join) order_by.join = opts.join;
199             if (opts.id_list) return_type = 'id_list';
200
201             var method = 'open-ils.pcrud.' + return_type + '.' + fm_class;
202             if(!opts.streaming) method += '.atomic';
203
204             var req_hash = dojo.mixin(
205                 opts, 
206                 { method : method,
207                   params : [ this.auth(), search, order_by ]
208                 }
209             );
210
211             if (!opts.async && !opts.timeout) req_hash.timeout = 10;
212
213             var _pcrud = this;
214             var req = this._session_request( req_hash );
215
216             if (!req.onerror)
217                 req.onerror = function (r) { throw js2JSON(r); };
218
219             // if it's an async call and the user does not care about 
220             // the responses, pull them off the network and discard them
221             if (!req_hash.timeout && !req.oncomplete)
222                 req.oncomplete = function (r) { while(r.recv()){}; };
223
224             req.send();
225
226             // for synchronous calls with no handlers, return the first received value
227             if (req_hash.timeout && !opts.oncomplete && !opts.onresponse) {
228                 var resp = req.recv();
229                 if(resp) return resp.content();
230                 return null;
231             }
232
233             return req;
234         },
235
236         _CUD : function ( method /* 'create' or 'update' or 'delete' */, list /* Fieldmapper object */, opts /* Option hash */) {
237             if(!opts) opts = {};
238
239             if (dojo.isArray(list)) {
240                 if (list.classname) list = [ list ];
241             } else {
242                 list = [ list ];
243             }
244
245             if (!this.connected) this.connect();
246
247             var _pcrud = this;
248             var _return_list = [];
249
250             function _CUD_recursive ( obj_list, pos, final_complete, final_error ) {
251                 var obj = obj_list[pos];
252                 var req_hash = {
253                     method : 'open-ils.pcrud.' + method + '.' + obj.classname,
254                     params : [ _pcrud.auth(), obj ],
255                     onerror : final_error || function (r) { _pcrud.disconnect(); throw '_CUD: Error creating, deleting or updating ' + js2JSON(obj); }
256                 };
257
258                 var req = _pcrud.session.request( req_hash );
259                 req._final_complete = final_complete;
260                 req._final_error = final_error;
261
262                 if (++pos == obj_list.length) {
263                     req.oncomplete = function (r) {
264                         var res = r.recv();
265
266                         if ( res && res.content() ) {
267                             _return_list.push( res.content() );
268                             _pcrud.session.request({
269                                 method : 'open-ils.pcrud.transaction.commit',
270                                 timeout : 10,
271                                 params : [ _pcrud.auth() ],
272                                 onerror : function (r) {
273                                     _pcrud.disconnect();
274                                     throw 'Transaction commit error';
275                                 },      
276                                 oncomplete : function (r) {
277                                     var res = r.recv();
278                                     if ( res && res.content() ) {
279                                         if(req._final_complete)
280                                             req._final_complete(req, _return_list);
281                                         _pcrud.disconnect();
282                                     } else {
283                                         _pcrud.disconnect();
284                                         throw 'Transaction commit error';
285                                     }
286                                 },
287                             }).send();
288                         } else {
289                             _pcrud.disconnect();
290                             throw '_CUD: Error creating, deleting or updating ' + js2JSON(obj);
291                         }
292                     };
293
294                     req.onerror = function (r) {
295                         if (r._final_error) r._final_error(r);
296                         _pcrud.disconnect();
297                         throw '_CUD: Error creating, deleting or updating ' + js2JSON(obj);
298                     };
299
300                 } else {
301                     req._pos = pos;
302                     req._obj_list = obj_list;
303                     req.oncomplete = function (r) {
304                         var res = r.recv();
305                         if ( res && res.content() ) {
306                             _return_list.push( res.content() );
307                             _CUD_recursive( r._obj_list, r._pos, r._final_complete );
308                         } else {
309                             _pcrud.disconnect();
310                             throw '_CUD: Error creating, deleting or updating ' + js2JSON(obj);
311                         }
312                     };
313                     req.onerror = function (r) {
314                         if (r._final_error) r._final_error(r);
315                         _pcrud.disconnect();
316                         throw '_CUD: Error creating, deleting or updating ' + js2JSON(obj);
317                     };
318                 }
319
320                 req.send();
321             }
322
323             var f_complete = opts.oncomplete;
324             var f_error = opts.onerror;
325
326             this.session.request({
327                 method : 'open-ils.pcrud.transaction.begin',
328                 timeout : 10,
329                 params : [ _pcrud.auth() ],
330                 onerror : function (r) {
331                     _pcrud.disconnect();
332                     throw 'Transaction begin error';
333                 },      
334                 oncomplete : function (r) {
335                     var res = r.recv();
336                     if ( res && res.content() ) {
337                         _CUD_recursive( list, 0, f_complete, f_error );
338                     } else {
339                         _pcrud.disconnect();
340                         throw 'Transaction begin error';
341                     }
342                 },
343             }).send();
344
345             return _return_list;
346
347         },
348
349         create : function ( list, opts ) {
350             return this._CUD( 'create', list, opts );
351         },
352
353         update : function ( list, opts ) {
354             var id_list = this._CUD( 'update', list, opts );
355             var obj_list = [];
356
357             for (var idx = 0; idx < id_list.length; idx++) {
358                 obj_list.push(
359                     this.retrieve( list[idx].classname, id_list[idx] )
360                 );
361             }
362
363             return obj_list;
364         },
365
366         /* 
367          * 'delete' is a reserved keyword in JavaScript and can't be used
368          * in browsers like IE or Chrome, so we define a safe synonym
369      * NOTE: delete() is now removed -- use eliminate instead
370
371         delete : function ( list, opts ) {
372             return this._CUD( 'delete', list, opts );
373         },
374
375          */
376         eliminate: function ( list, opts ) {
377             return this._CUD( 'delete', list, opts );
378         },
379
380         apply : function ( list, opts ) {
381             this._auto_CUD( list, opts );
382         },
383
384         _auto_CUD : function ( list /* Fieldmapper object */, opts /* Option hash */) {
385
386             if(!opts) opts = {};
387
388             if (dojo.isArray(list)) {
389                 if (list.classname) list = [ list ];
390             } else {
391                 list = [ list ];
392             }
393
394             if (!this.connected) this.connect();
395
396             var _pcrud = this;
397
398             function _auto_CUD_recursive ( obj_list, pos, final_complete, final_error ) {
399                 var obj = obj_list[pos];
400
401                 var method;
402                 if (obj.ischanged()) method = 'update';
403                 if (obj.isnew())     method = 'create';
404                 if (obj.isdeleted()) method = 'delete';
405                 if (!method) {
406                     return _auto_CUD_recursive(obj_list, pos+1, final_complete, final_error);
407                 }
408
409                 var req_hash = {
410                     method : 'open-ils.pcrud.' + method + '.' + obj.classname,
411                     timeout : 10,
412                     params : [ _pcrud.auth(), obj ],
413                     onerror : final_error || function (r) { _pcrud.disconnect(); throw '_auto_CUD: Error creating, deleting or updating ' + js2JSON(obj); }
414                 };
415
416                 var req = _pcrud.session.request( req_hash );
417                 req._final_complete = final_complete;
418                 req._final_error = final_error;
419
420                 if (++pos == obj_list.length) {
421                     req.oncomplete = function (r) {
422
423                         _pcrud.session.request({
424                             method : 'open-ils.pcrud.transaction.commit',
425                             timeout : 10,
426                             params : [ _pcrud.auth() ],
427                             onerror : function (r) {
428                                 _pcrud.disconnect();
429                                 throw 'Transaction commit error';
430                             },      
431                             oncomplete : function (r) {
432                                 var res = r.recv();
433                                 if ( res && res.content() ) {
434                                     if (r._final_complete) 
435                                         req._final_complete(req, _return_list);
436                                     _pcrud.disconnect();
437                                 } else {
438                                     _pcrud.disconnect();
439                                     throw 'Transaction commit error';
440                                 }
441                             },
442                         }).send();
443                     };
444
445                     req.onerror = function (r) {
446                         if (r._final_error) r._final_error(r);
447                         _pcrud.disconnect();
448                     };
449
450                 } else {
451                     req._pos = pos;
452                     req._obj_list = obj_list;
453                     req.oncomplete = function (r) {
454                         var res = r.recv();
455                         if ( res && res.content() ) {
456                             _auto_CUD_recursive( r._obj_list, r._pos, r._final_complete, r._final_error );
457                         } else {
458                             _pcrud.disconnect();
459                             throw '_auto_CUD: Error creating, deleting or updating ' + js2JSON(obj);
460                         }
461                     };
462                 }
463
464                 req.send();
465             }
466
467             var f_complete = opts.oncomplete;
468             var f_error = opts.onerror;
469
470             this.session.request({
471                 method : 'open-ils.pcrud.transaction.begin',
472                 timeout : 10,
473                 params : [ _pcrud.auth() ],
474                 onerror : function (r) {
475                     _pcrud.disconnect();
476                     throw 'Transaction begin error';
477                 },      
478                 oncomplete : function (r) {
479                     var res = r.recv();
480                     if ( res && res.content() ) {
481                         _auto_CUD_recursive( list, 0, f_complete, f_error );
482                     } else {
483                         _pcrud.disconnect();
484                         throw 'Transaction begin error';
485                     }
486                 },
487             }).send();
488         }
489
490     });
491 }
492
493