-
Notifications
You must be signed in to change notification settings - Fork 3
/
CRUDModel.js
2097 lines (2007 loc) · 76.5 KB
/
CRUDModel.js
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* nl.barrydam.model.CRUDModel
* @author Barry Dam
* @version 1.3.0
* add this file to your project folder library/bd/model/
* In your Component.js add:
* jQuery.sap.registerModulePath("nl.barrydam", "library/bd/");
* jQuery.sap.require("nl.barrydam.model.CRUDModel");
*/
(function($, windows, undefined){
jQuery.sap.declare('nl.barrydam.model.CRUDModel');
jQuery.sap.require("jquery.sap.storage");
sap.ui.define(
"nl/barrydam/model/CRUDModel",
[
"sap/ui/model/json/JSONModel",
"sap/ui/core/util/Export",
"sap/ui/core/util/ExportTypeCSV",
],
function(JSONModel, Export, ExportTypeCSV) {
"use strict";
var _variables = { // internal variables
mDefaultParameters : {
// the API auto generates setters and getters for all parameters
// for example user will have a setUsername(value) and getUsername() method available
// these params can be passed along with the constructor
bindingMode : "TwoWay", // only TwoWay or OneWay
password : '', // password when a auto-login is needed
primaryKey : "id", // Default db primaryKey
serviceUrl : '', // URL To api
serviceUrlParams : {}, // additional URL params
useBatch : false, //when true all POST PUT and DELETE requests will be sent in batch requests (default = false),
user : '' // username when a auto-login is needed
},
// these events will be auto created
mSupportedEvents : [
"Login", // attachLogin attachLoginOnce fireLogin
"Logout", // attachLogout attachLogoutOnce fireLogout
"MetadataFailed", // attachMetadataFailed attachMetadataFailedOnce fireMetaDatafailed
"MetadataLoaded", // attachMetadataLoaded attachMetadataLoadedOnce fireMetadataLoaded
"Reload", // attachReload attachReloadOnce fireReload
"RequestCompleted", // attachRequestCompleted attachRequestCompletedOnce fireRequestCompleted
"Updated", // attachUpdated attachUpdatedOnce fireUpdated
"TableDataChanged" // attachTableDataChanged attachTableDataChangedOnce fireTableDataChanged
],
mUnsupportedOperations : ["loadData"], // methods from JSONModel which cannot be used
csrf: null // csrf token
},
_methods = {}; // internal methods which can be used inside the CRUDModel methods
// _base64 enc
var _base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = _base64._utf8_encode(String(input));
while (i < input.length) {
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 + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
decode: function(input) {
var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) { output = output + String.fromCharCode(chr2); }
if (enc4 != 64) { output = output + String.fromCharCode(chr3); }
}
return _base64._utf8_decode(output);
},
_utf8_encode: function(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
_utf8_decode: function(utftext) {
var string = "", i = 0, c = 0, c1 = 0, c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
/**
* magic _set methods *used in constructor and createSettersAndGetters,
* @param {object} Proxy refers to the CRUDModel object
* @param {string} key key
* @param {string} value value
*/
_methods._set = function(oProxy, key, value) {
switch (key) {
// determine the service base url and its parameters
case 'serviceUrl' :
var aUrl = value.split('?');
if (aUrl.length > 1) {
// re-assign the value and add a trailing slash if not present
value = aUrl[0] + ( (aUrl[0].slice(-1) !== "/") ? "/" : "" );
if (aUrl[1]) {
var mServiceUrlParams = oProxy.getServiceUrlParams();
var aUrlParameters = aUrl[1].split('&');
for (var keyUrlParameter in aUrlParameters) {
var aUrlParameter = aUrlParameters[keyUrlParameter].split('=');
mServiceUrlParams[aUrlParameter[0]] = aUrlParameter[1] || false;
}
oProxy.setServiceUrlParams(mServiceUrlParams);
}
}
break;
case 'bindingMode':
value = (["TwoWay", "OneWay"].indexOf(value) !== -1) ? value : "TwoWay";
oProxy.setDefaultBindingMode(value);
break;
}
// store in settings
oProxy._mSettings[key] = value;
};
/**
* magic _get methods *used in constructor and createSettersAndGetters,
* @param {object} Proxy refers to the CRUDModel object
* @param {string} key key
* @param {string} value value
*/
_methods._get = function(oProxy, key) {
var value;
switch (key) {
case "primaryKey" :
// if primary key is set by metadata
if (arguments.length >= 3 && arguments[2] in oProxy._oCRUDdata.oPrimaryKeys) {
value = oProxy._oCRUDdata.oPrimaryKeys[arguments[2]];
}
break;
default:
value = oProxy._mSettings[key];
break;
}
return value;
};
/**
* Creates getters and setters for the allowed to change params of the _mSettings object
* This method is only called once by the CRUDModel constructor
* @example primaryKey will generate getPrimaryKey and setPrimaryKey
*
* @param object oProxy the created nl.barydam.CRUDModel object
*/
_methods.createSettersAndGetters = function(oProxy) {
$.each(_variables.mDefaultParameters, function(key) { // $.each used in stead of for! else key would be allways the last iteration
var f = key.charAt(0).toUpperCase(),
sSetter = 'set'+f+key.substr(1),
sGetter = 'get'+f+key.substr(1);
oProxy[sSetter] = function(value) {
_methods._set(oProxy, key, value);
};
oProxy[sGetter] = function() {
var aNew = [oProxy, key];
if (arguments.length) {
$.each(arguments, function(i, arg) {
aNew.push(arg);
});
}
return _methods._get.apply(this, aNew);
};
});
};
/**
* Creates a new debug-level entry in the log with the given message, details and calling component.
* @param {string} sMessage Message text to display
* @param {string} Method Method which calls the log
* @return {object} jQuery.sap.log.Logger The log instance
*/
_methods.logDebug = function(sMessage, Method) {
return jQuery.sap.log.debug(
sMessage,
"",
"com.barydam.sap.ui.model.json.CRUDModel"+((Method) ? "."+Method : "")
);
};
/**
* Creates a new error-level entry in the log with the given message, details and calling component.
* @param {string} sMessage Message text to display
* @param {string} Method Method which calls the log
* @return {object} jQuery.sap.log.Logger The log instance
*/
_methods.logError = function(sMessage, Method) {
return jQuery.sap.log.error(
sMessage,
"",
"com.barydam.sap.ui.model.json.CRUDModel"+((Method) ? "."+Method : "")
);
};
/**
* Helper method for bindList bindProperty and bindTree methods
* @param {object} oProxy oProxy the created nl.barydam.CRUDModel object
* @param {string} sPath
* @param {array} aSorters
* @param {array} aFilters
* @return {xhr object}
*/
var __reloadExecBind = []; // hold the binds and will be reloaded when this.reload is called
_methods.reloadBinds = function(sPath, fnSuccess, fnError) {
var fnSuccessCallback = fnSuccess,
fnErrorCallback = fnError;
if (typeof sPath !== "string") {
fnSuccessCallback = sPath;
fnErrorCallback = fnSuccess;
}
fnSuccessCallback = (typeof fnSuccessCallback == "function") ? fnSuccessCallback : function(){};
fnErrorCallback = (typeof fnErrorCallback == "function") ? fnErrorCallback : function(){};
if (__reloadExecBind.length === 0) {
fnSuccessCallback();
} else {
var aPromises = [];
$.each(__reloadExecBind, function(i, o) {
if (typeof sPath === "string") {
var mPathRequested = _methods.parsePath(sPath),
mPathCurrent = _methods.parsePath(o.sPath);
if (mPathRequested.Table == mPathCurrent.Table) {
aPromises.push(_methods.execBind(o.oProxy, o.sPath, o.aSorters, o.aFilters, true));
}
} else {
aPromises.push(_methods.execBind(o.oProxy, o.sPath, o.aSorters, o.aFilters, true));
}
});
$.when.apply($, aPromises)
.done(function() {
var aErrors = [];
$.each(arguments, function(i, a) {
if (a[1] == 'error') {
aErrors.push(a);
}
});
if (aErrors.length) {
fnErrorCallback(aErrors);
} else {
fnSuccessCallback();
}
})
.fail(function() {
fnErrorCallback.apply(this, arguments);
});
}
};
_methods.execBind = function(oProxy, sPath, aSorters, aFilters, bAttachReload) {
var mPath = _methods.parsePath(sPath),
sUrl = mPath.Table;
if (! sUrl) { return; }
// Filter
if ( $.isArray(aFilters) && aFilters.length ) {
sUrl += "?"+_methods.parseUI5Filters(aFilters);
}
if (! bAttachReload) { // refresh after login
oProxy.attachLogin(function() {
//_methods.execBind(oProxy, sPath, aSorters, aFilters, true);
oProxy.reload();
});
__reloadExecBind.push({
oProxy : oProxy,
sPath : sPath,
aSorters : aSorters,
aFilters : aFilters
});
// commented this out cuz it resulted in 2 reloads
// oProxy.attachReload(function() {
// console.log(arguments);
// _methods.execBind(oProxy, sPath, aSorters, aFilters, true);
// });
}
return oProxy._serviceCall(
sUrl,
{
type: "GET",
success: function(mResponse) {
// set property of parent method
JSONModel.prototype.setProperty.call(
oProxy,
"/"+mPath.Table,
$.extend(
true,
_methods.parseCRUDresultList(oProxy, mPath.Table, mResponse),
oProxy.getProperty("/"+mPath.Table)
)
);
// fire event
oProxy.fireTableDataChanged({
table : mPath.Table
});
}
}
);
};
_methods.localStorageSaveCSRF = function(csrf) {
if (! jQuery.sap.storage.isSupported())
return;
var oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
if (csrf) {
oStorage.put('csrf', _base64.encode(csrf));
} else {
oStorage.remove('csrf');
}
};
_methods.localStorageGetCSRF = function() {
if (! jQuery.sap.storage.isSupported())
return;
var oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local),
csrf = oStorage.get("csrf");
if (! csrf) {
return false;
}
return _base64.decode(csrf);
};
/**
* Creates a new model and check the columns with the metadata (if present)
* @param {object} oProxy Refers to CRUDModel object
* @param {string} sTableName Table name
* @param {object} mData Unprocessed entry
* @return {object} mData Processed entry
*/
_methods.generateCreateByMetadata = function(oProxy, sTableName, mData) {
mData = mData || {};
if (sTableName in oProxy._oCRUDdata.oColumns) {
var oNew = {};
$.each(oProxy._oCRUDdata.oColumns[sTableName], function(i, oColumn) {
var sValue = oNew[oColumn.name];
// Number? 0 eq false so check if it is an number
if (! isNaN(mData[oColumn.name])) {
sValue = mData[oColumn.name];
} else {
sValue = mData[oColumn.name] || "";
}
oNew[oColumn.name] = _methods.parseCRUDGetColumn(oProxy, sTableName, oColumn.name, sValue);
});
if (Object.keys(oNew).length) {
mData = oNew;
}
}
return mData;
};
/**
* Parse data received from api
*/
_methods.parseCRUDGetData = function(oProxy, sTableName, mData) {
if (typeof mData !== "object" || Object.keys(mData).length === 0) {
return mData;
}
mData = $.extend(true, {}, mData);
for (var sColumn in mData) {
mData[sColumn] = _methods.parseCRUDGetColumn(oProxy, sTableName, sColumn, mData[sColumn]);
}
return mData;
};
_methods.parseCRUDGetColumn = function(oProxy, sTableName, sColumn, sValue) {
if ( (! isNaN(sValue) || sValue) && sTableName in oProxy._oCRUDdata.oColumns && sColumn in oProxy._oCRUDdata.oColumns[sTableName]) {
switch (oProxy._oCRUDdata.oColumns[sTableName][sColumn].type) {
case "date":
case "datetime":
case "timestamp":
sValue = (! sValue || sValue == "0000-00-00") ? null : new Date(sValue) ;
break;
default: // nothing
break;
}
}
return sValue;
};
/**
* Parse the data before sending it back to the api
*/
_methods.parseCRUDPostData = function(oProxy, sTableName, mData) {
if (typeof mData !== "object" || Object.keys(mData).length === 0) {
return mData;
}
mData = $.extend(true, {}, mData);
for (var sColumn in mData) {
if (mData[sColumn] && sTableName in oProxy._oCRUDdata.oColumns && sColumn in oProxy._oCRUDdata.oColumns[sTableName]) {
mData[sColumn] = _methods.parseCRUDPostColumn(oProxy, sTableName, sColumn, mData[sColumn]);
}
}
return mData;
};
_methods.parseCRUDPostColumn = function(oProxy, sTableName, sColumn, sValue) {
if (sValue && sTableName in oProxy._oCRUDdata.oColumns && sColumn in oProxy._oCRUDdata.oColumns[sTableName]) {
switch (oProxy._oCRUDdata.oColumns[sTableName][sColumn].type) {
case "date":
if (sValue instanceof Date) {
sValue = isNaN(sValue.getTime()) ? "" : sValue.toISOString().substring(0, 10);
}
break;
case "datetime":
case "timestamp":
if (sValue instanceof Date) {
sValue = isNaN(sValue.getTime()) ? "" : sValue.toISOString().substring(0, 19).replace('T', ' ');
}
break;
default: // nothing
break;
}
}
return sValue;
};
/**
* Parses CRUD results List - List results and converts them to json data
* @param {object} oProxy refers to CRUDModel object
* @param {string} sTableName Table name
* @param {object} mResponse Responsedata from CRUD
* @return {object} processed json object
*/
_methods.parseCRUDresultList = function(oProxy, sTableName, mResponse) {
if (typeof mResponse == "object" && sTableName in mResponse && 'records' in mResponse[sTableName] && 'columns' in mResponse[sTableName]) {
var mRows = mResponse[sTableName].records,
mColums = mResponse[sTableName].columns;
// try to save columns
if (! (sTableName in oProxy._oCRUDdata.oColumns)) {
oProxy._oCRUDdata.oColumns[sTableName] = {};
$.each(mColums, function(index, sColumn){
if (sColumn !== oProxy.getPrimaryKey(sTableName)) {
oProxy._oCRUDdata.oColumns[sTableName][sColumn] = {
name:sColumn,
type: "string"
};
}
});
}
// process rows
var mData = {};
for (var i in mRows) {
var mNewData = {},
mRow = mRows[i];
for (var iR in mRow) {
mNewData[mColums[iR]] = _methods.parseCRUDGetColumn(oProxy, sTableName, mColums[iR], mRow[iR]);
}
mData[mNewData[oProxy.getPrimaryKey(sTableName)]] = mNewData;
}
return mData;
} else {
return {};
}
};
/**
* process the metadata
* @param {object} oProxy refers to CRUDModel object
* @param {[type]} mListResult [description]
* @return {void}
*/
_methods.processMetadata = function(oProxy, mListResult) {
if (! ("paths" in mListResult)) {
return;
}
var oReturn = {};
$.each(mListResult.paths, function(sPath, o){
var mPath = _methods.parsePath(sPath),
sTable = mPath.Table;
if (mPath.Id) { return; /*{id}*/ }
oReturn[sTable] = {};
if (("post" in o) && ("parameters" in o.post) && typeof o.post.parameters[0] == "object") {
var aColumns = o.post.parameters[0].schema.properties;
for (var sCol in aColumns) {
// check if columnn is primary key
if ("x-primary-key" in aColumns[sCol]) {
oProxy._oCRUDdata.oPrimaryKeys[sTable] = sCol;
} else {
oReturn[sTable][sCol] = {
name: sCol,
type: aColumns[sCol]["x-dbtype"] || "string"
};
}
}
}
if (("get" in o) &&
("responses" in o.get) &&
("200" in o.get.responses) &&
("schema" in o.get.responses["200"]) &&
("items" in o.get.responses["200"].schema) &&
("properties" in o.get.responses["200"].schema.items) &&
typeof o.get.responses["200"].schema.items.properties == "object" &&
Object.keys(o.get.responses["200"].schema.items.properties).length
) {
var oItems = o.get.responses["200"].schema.items.properties;
for (var sColName in oItems) {
if (! (sColName in oReturn[sTable])) {
oReturn[sTable][sColName] = {"name": sColName, "type": ""};
}
oReturn[sTable][sColName].type = oItems[sColName]["x-dbtype"] || "string";
// try to find the primary key if it's not allready found in the post
if (! (sTable in oProxy._oCRUDdata.oPrimaryKeys) && "x-primary-key" in oItems[sColName]) {
oProxy._oCRUDdata.oPrimaryKeys[sTable] = sColName;
}
}
}
// could not find primary key
if (! (sTable in oProxy._oCRUDdata.oPrimaryKeys)) { // cant create by this oProxy since there is no primary Id
delete oReturn[sTable];
_methods.logDebug("The primary is unkown for table:"+ sTable, "parseMetadata");
return;
}
});
oProxy._oCRUDdata.oColumns = Object.keys(oReturn).length ? oReturn : null ;
};
/**
* Example /student/1
* returns
* {
* Table: "student",
* Id: "1",
* Path: "/student/1"
* }
* @param {string} path
* @return {object} { Table: 'tablename', Id: "id", Path: "/tablename/id" }
*/
_methods.parsePath = function(sPath) {
// turn /example('1') to /example/1
sPath = sPath.replace("('", "/").replace("')", "");
// turn /example("1") to /example/1
sPath = sPath.replace("(\"", "/").replace("\")", "");
// turn /example(1) to /example/1
sPath = sPath.replace("(", "/").replace(")", "");
// Split params (after ? )
var aPath = sPath.split("?"),
sParams = "";
if (aPath.length > 1) {
sPath = aPath[0];
sParams = aPath[1];
}
aPath = sPath.split("/");
var oReturn = {
Table : "",
Id : "",
Path : "",
Parameters: sParams
};
if (aPath.length === 0) {
return oReturn;
}
if (aPath[0] === "") {
aPath.shift();
}
if (aPath.length === 0) {
return oReturn;
}
oReturn.Table = aPath[0];
oReturn.Path = "/"+oReturn.Table;
if (aPath.length > 1) {
oReturn.Id = aPath[1];
oReturn.Path += "/"+oReturn.Id;
}
return oReturn;
};
/**
* Converts sap.ui.model.Filter to API filter string
* @param {array} afilters array containing sap.ui.model.Filter objects
* @returns {string} filter string example filter=naam,eq,Barry
*/
_methods.parseUI5Filters = function(aFilters) {
if (! (aFilters instanceof Array) || aFilters.length === 0) {
return "";
}
function parse(oFilter) {
var oOperators = {
BT : "bt",
Contains : "cs",
EndsWith : "ew",
EQ : "eq",
GE : "ge",
GT : "gt",
LE : "le",
LT : "lt",
NE : "neq", // NOT SUPPORTED BY PHP API
StartsWith : "sw",
};
return oFilter.sPath+','+oOperators[oFilter.sOperator]+','+oFilter.oValue1+((oFilter.sOperator=='BT')?','+oFilter.oValue2:'');
}
var aString = [],
sSatisfy = (aFilters.length > 1)? "all": "any"; // default xml view multiple filters are AND conjunctions
$.each(aFilters, function(i, oFilter) {
if (oFilter instanceof sap.ui.model.Filter) {
if (oFilter._bMultiFilter) {
for (var iSub in oFilter.aFilters) {
aString.push(parse(oFilter.aFilters[iSub]));
}
sSatisfy = (typeof oFilter.bAnd != "undefined") ? ((oFilter.bAnd)?"all":"any") : "all" ;
} else {
aString.push(parse(oFilter));
}
}
});
var sFilter = (aString.length>1) ? "filter[]=" : "filter=";
return sFilter+aString.join("&"+sFilter)+((aString.length>1)?"&satisfy="+sSatisfy:"");
};
/**
*
*/
var CRUDModel = JSONModel.extend(
'nl.barrydam.model.CRUDModel',
{
_loggedIn:null,
_oCRUDdata : {
oPrimaryKeys: {
/**
*
*/
},
oColumns: {
/* example
student: ["id", "name", "birtday", "gender"],
school: ["id", "name", "address", ....etc]
*/
},
oColumnTypes: {
/* example
student: {
id : "int",
name : "string",
birthday : "date",
gender : "string"
}
*/
},
oBatch: {
/*
PUT: {
student: {
1: {
id : 1,
name: "Barry"
}
}
}
POST: : {
student: {
_CREATED_ID_: {
data....
}
}
}
DELETE: {
student: [1, 3, 4 ..] array of id's to delete
}
*/
}
},
/**
* settings object is set in the constructor and is a merge of
* - _variables.mDefaultParameters (defined within this scope)
* - mParameters (passed in constructor)
* - and _mSettings
* all values can be set and get by magic methods
* @type {Object}
*/
_mSettings : {},
/**
* Metadata settings
* @type {Object}
*/
// metadata : {
// publicMethods : ["submitChanges", "resetChanges", "reload", "remove", "update"]
// },
/**
* Constructor fired on object creation
* @param string sServiceUrl The URL to the JSON service
* @param object mParameters overwrite settings for the _variables.mDefaultParameters value
*/
constructor: function(sServiceUrl, mParameters) {
JSONModel.apply(this); // do not pass arguments
// create setters and getters on object creation
_methods.createSettersAndGetters(this);
// reset settings (needed for getOne method)
this._mSettings = {
};
// set service url
this.setServiceUrl(sServiceUrl);
if (typeof mParameters !== 'object')
mParameters = {};
// Set the settings and check if passed param is allowed to set
// any passed parameter which is not in the _variables.mDefaultParameters
// will not be stored
var aDefaultParametersKeys = Object.keys(_variables.mDefaultParameters);
for (var kParameter in mParameters) {
if (aDefaultParametersKeys.indexOf(kParameter) !== -1 && typeof mParameters[kParameter] === typeof _variables.mDefaultParameters[kParameter]) {
_methods._set(this, kParameter, mParameters[kParameter]);
}
}
// merge the mDefaultSettings with the _mSettings to make sure whe have every needed param
this._mSettings = $.extend(true, {}, _variables.mDefaultParameters, this._mSettings);
// try to set the csrf from local storage
// so if your logged in the api, you do not need to re enter your credentials everytime you reload the page
var sCsrfLocalStorage = _methods.localStorageGetCSRF();
_variables.csrf = sCsrfLocalStorage;
// metadata
var that = this,
fnLoadMetadata = function(fnOnsuccess) {
that._serviceCall("", {
success: function(m) {
_methods.processMetadata(that, m);
that.fireMetadataLoaded();
if (typeof fnOnsuccess == "function") {
fnOnsuccess();
}
},
error: function(xhr, textStatus, httpStatus) {
that.fireMetadataFailed();
// not logged in? load metadata after login
if (httpStatus == "Unauthorized" || xhr.status == 401) {
that.attachLoginOnce(function(){
fnLoadMetadata();
});
}
},
async: (that.getUser() && that.getPassword()) ? false : ((sCsrfLocalStorage) ? true : false)
});
};
// user settings passed in constructor
if (this.getUser() && this.getPassword()) {
this.login(
this.getUser(),
this.getPassword(),
{
async: true // keep this true
}
);
}
fnLoadMetadata(function onSuccess(){
if (sCsrfLocalStorage) { // if this has an value, the api uses user credentials
that.fireLogin();
}
});
}
}
);
/**
* Disable parent methods which are not allowed to use
*/
if (_variables.mUnsupportedOperations.length) {
var fnDisableOperation = function(sOperation) {
if (! CRUDModel.hasOwnProperty(sOperation)) { return; }
CRUDModel.prototype[sOperation] = function() {
throw new Error("Unsupported operation: v4.ODataModel#isList");
};
};
$.each(_variables.mUnsupportedOperations, function(i, sOperation) {
fnDisableOperation(sOperation);
});
}
/**
* Create Event attachers and detachers and fires
*/
if (_variables.mSupportedEvents.length) {
var fnCreateEvents = function(sEventId) {
sEventId = sEventId.charAt(0).toUpperCase() + sEventId.slice(1);
CRUDModel.prototype["attach"+sEventId] = function(oData, fnFunction, oListener) {
var oEvent = this.attachEvent(sEventId, oData, fnFunction, oListener);
/* sometimes the login and logout events are attached after the fire */
if (sEventId === "Login" && this._loggedIn) {
this.fireLogin();
} else if (sEventId === "Logout" && this._loggedIn === false) { // important to check on false (null is set by default)
this.fireLogout();
}
return oEvent;
};
CRUDModel.prototype["attach"+sEventId+"Once"] = function(oData, fnFunction, oListener) {
var oEvent = this.attachEventOnce(sEventId, oData, fnFunction, oListener);
if (sEventId === "Login" && this._loggedIn) {
this.fireLogin();
} else if (sEventId === "Logout" && this._loggedIn === false) { // important to check on false (null is set by default)
this.fireLogout();
}
return oEvent;
};
CRUDModel.prototype["detach"+sEventId] = function(oData, fnFunction, oListener) {
return this.detachEvent(sEventId, oData, fnFunction, oListener);
};
CRUDModel.prototype["detach"+sEventId+"Once"] = function(oData, fnFunction, oListener) {
return this.detachEventOnce(sEventId, oData, fnFunction, oListener);
};
CRUDModel.prototype["fire"+sEventId] = function(mParameters, bAllowPreventDefault, bEnableEventBubbling) {
_methods.logDebug(sEventId+" event fired");
return this.fireEvent(sEventId, mParameters, bAllowPreventDefault, bEnableEventBubbling);
};
};
$.each(_variables.mSupportedEvents, function(i, sEvent) {
fnCreateEvents(sEvent);
});
}
/**
* Call to the service
* @param {string} sUrl [description]
* @param {object} mRequestParams [description]
* @return {xhr}
*/
var __oServiceCalls = {};
CRUDModel.prototype._serviceCall = function(sUrl, mRequestParams) {
mRequestParams = mRequestParams || {};
mRequestParams.error = (typeof mRequestParams.error == "function") ? mRequestParams.error : function(){} ;
mRequestParams.success = (typeof mRequestParams.success == "function") ? mRequestParams.success : function(){} ;
var aSplitGetParams = sUrl.split("?"),
url = aSplitGetParams.shift(),
oURLParams = this.getServiceUrlParams(),
bAsync = ("async" in mRequestParams) ? mRequestParams.async : true,
aGetParams = [],
that = this;
// remove first slash
if (url && url.charAt(0) == "/") {
url.substr(1);
}
// prepend serviceUrl
url = this.getServiceUrl()+url;
// prepare url params
if (Object.keys(oURLParams).length) { // first existing serviceUrlParams
for (var i in oURLParams) {
aGetParams.push(i+'='+oURLParams[i]);
}
}
if (aSplitGetParams.length) { // second the params passed to the _serviceCall method
aGetParams.push(aSplitGetParams.join("?"));
}
if (aGetParams.length) { // rebuild the URL
url = url+'?'+aGetParams.join("&");
}
var iServiceCallId = Date.now();
// execute the request
var mHeaders = {
"Accept-Language": sap.ui.getCore().getConfiguration().getLanguage()
};
if (_variables.csrf) {
mHeaders["X-XSRF-TOKEN"] = _variables.csrf;
}
var mAjax = {
type : mRequestParams.type || "GET",
url : url,
//data : ("data" in mRequestParams) ? JSON.stringify(mRequestParams.data) : {},
data : ("data" in mRequestParams) ? mRequestParams.data : {},
dataType : "json",
cache : false, // NEVER!
async : bAsync,
success : mRequestParams.success,
headers : mHeaders,
error : function(xhr, textStatus, httpStatus) {
if (httpStatus == "Unauthorized" || xhr.status == 401) {
if (bAsync) {
delete __oServiceCalls[iServiceCallId];
}
// abort all asynchronous service calls
$.each(__oServiceCalls, function(i, xhr) {
xhr.abort();
});
// fire logout
// IMPORTANT: allways put this AFTER above sync abortions
that._loggedIn = false;
that.fireLogout();
}
mRequestParams.error.apply(this, arguments);
},
complete : function(xhr) {
// request is completed so we can remove it from the servicecall pool
if (bAsync) {
delete __oServiceCalls[iServiceCallId];
}
var mPath = _methods.parsePath(sUrl);
that.fireRequestCompleted({
url : url,
path : mPath,
type : mRequestParams.type || "GET",
success : (xhr.status == 200),
async : bAsync
});
},
beforeSend: function(jqXhr) {
// add to servicecall array so we can abort them in case of logged out
if (bAsync) {
__oServiceCalls[iServiceCallId] = jqXhr;
}
}
};
// needed for upload to work
if ("processData" in mRequestParams) {
mAjax.processData = mRequestParams.processData;
}
if ("contentType" in mRequestParams) {
mAjax.contentType = mRequestParams.contentType;
}
// exec ajax req and return xhr object;
return $.ajax(mAjax);
};
/**
* @see sap.ui.model.json.JSONModel.bindList
* Lists are allways called from the api
*/
CRUDModel.prototype.bindList = function(sPath, oContext, aSorters, aFilters, mParameters) {
_methods.execBind(this, this.resolve(sPath, oContext), aSorters, aFilters);
return JSONModel.prototype.bindList.apply(this, arguments);
};
/**
* @see sap.ui.model.json.JSONModel.bindProperty
* Only called from the api when needed
*/
CRUDModel.prototype.bindProperty = function(sPath, oContext, mParameters) {
var oParent = JSONModel.prototype.bindProperty.apply(this, arguments);
sPath = this.resolve(sPath, oContext);
if (sPath) {
var mPath = _methods.parsePath(sPath);
if (! mPath.Id) {
return oParent;
}
var mModel = this.getProperty("/"+mPath.Table),
that = this;
if (typeof mModel == "undefined" || ! (mPath.Id in mModel)) {
_methods.execBind(this, mPath.Table, null, [
new sap.ui.model.Filter(this.getPrimaryKey(mPath.Table), "EQ", mPath.Id)
]);
}
}
return oParent;
};