-
Notifications
You must be signed in to change notification settings - Fork 38
/
jdrupal.js
1397 lines (1226 loc) · 33.1 KB
/
jdrupal.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
// Initialize the jDrupal object.
var jDrupal = typeof jDrupal === 'undefined' ? {} : jDrupal;
/**
* Initializes the jDrupal JSON object.
*/
jDrupal.init = function() {
// General properties.
jDrupal.csrf_token = false;
jDrupal.sessid = null;
jDrupal.modules = {};
jDrupal.connected = false; // Will be equal to true after the system connect.
jDrupal.settings = {
sitePath: null,
basePath: '/'
};
};
// Init jDrupal.
jDrupal.init();
/**
* Get or set a jDrupal configuration setting.
* @param {String} name
* @returns {*}
*/
jDrupal.config = function(name) {
var value = typeof arguments[1] !== 'undefined' ? arguments[1] : null;
if (value) {
jDrupal.settings[name] = value;
return;
}
return jDrupal.settings[name];
};
jDrupal.sitePath = function() {
return jDrupal.settings.sitePath;
};
jDrupal.basePath = function() {
return jDrupal.settings.basePath;
};
jDrupal.restPath = function() {
return this.sitePath() + this.basePath();
};
jDrupal.path = function() {
return this.restPath().substr(this.restPath().indexOf('://')+3).replace('localhost', '');
};
/**
* Checks if we're ready to make a Services call.
* @return {Boolean}
*/
jDrupal.isReady = function() {
try {
var ready = !jDrupal.isEmpty(jDrupal.sitePath());
if (!ready) { console.log('sitePath not set in jdrupal.settings.js'); }
return ready;
}
catch (error) { console.log('jDrupal.isReady - ' + error); }
};
/**
* Returns true if given value is empty. A generic way to test for emptiness.
* @param {*} value
* @return {Boolean}
*/
jDrupal.isEmpty = function(value) {
if (value !== null && typeof value === 'object') { return Object.keys(value).length === 0; }
return (typeof value === 'undefined' || value === null || value == '');
};
/**
* Given a JS function name, this returns true if the function exists, false otherwise.
* @param {String} name
* @return {Boolean}
*/
jDrupal.functionExists = function(name) { return (eval('typeof ' + name) == 'function'); };
/**
* Checks if the needle string, is in the haystack array. Returns true if it is
* found, false otherwise. Credit: http://stackoverflow.com/a/15276975/763010
* @param {String|Number} needle
* @param {Array} haystack
* @return {Boolean}
*/
jDrupal.inArray = function (needle, haystack) {
try {
if (typeof haystack === 'undefined') { return false; }
if (typeof needle === 'string') { return (haystack.indexOf(needle) > -1); }
else {
var found = false;
for (var i = 0; i < haystack.length; i++) {
if (haystack[i] == needle) {
found = true;
break;
}
}
return found;
}
}
catch (error) { console.log('jDrupal.inArray - ' + error); }
};
/**
* Given something, this will return true if it's an array, false otherwise.
* @param {*} obj
* @returns {boolean}
* @see http://stackoverflow.com/a/1058753/763010
*/
jDrupal.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
/**
* Given an argument, this will return true if it is an int, false otherwise.
* @param {Number} n
* @return {Boolean}
*/
jDrupal.isInt = function(n) {
// @credit: http://stackoverflow.com/a/3886106/763010
if (typeof n === 'string') { n = parseInt(n); }
return typeof n === 'number' && n % 1 == 0;
};
/**
* Checks if incoming variable is a Promise, returns true or false.
* @param {Object} obj The variable to check.
* @returns {boolean}
*/
jDrupal.isPromise = function(obj) { return Promise.resolve(obj) == obj; };
/**
* Shuffle an array.
* @see http://stackoverflow.com/a/12646864/763010
* @param {Array} array
* @return {Array}
*/
jDrupal.shuffle = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
/**
* Javascript equivalent of php's time() function.
* @returns {number}
*/
jDrupal.time = function() {
var d = new Date();
return Math.floor(d / 1000);
};
/**
* Given a string, this will change the first character to lower case and return
* the new string.
* @param {String} str
* @return {String}
*/
jDrupal.lcfirst = function(str) {
str += '';
var f = str.charAt(0).toLowerCase();
return f + str.substr(1);
};
/**
* Given a string, this will change the first character to upper case and return
* the new string.
* @param {String} str
* @return {String}
*/
jDrupal.ucfirst = function(str) {
// @credit http://kevin.vanzonneveld.net
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
};
/**
* The jDrupal Module constructor prototype skeleton, which doesn't do anything since all module's implement their own
* constructors.
* @constructor
*/
jDrupal.Module = function() {
this.name = null;
};
/**
* Given a module name, this returns true if the module is enabled, false otherwise.
* @param {String} name The name of the module
* @return {Boolean}
*/
jDrupal.moduleExists = function (name) {
return typeof jDrupal.modules[name] !== 'undefined';
};
/**
* Determines which modules are implementing a hook. Returns an array with the names of the modules which are
* implementing this hook. If no modules implement the hook, it returns false.
* @param {String} hook
* @return {Array}
*/
jDrupal.moduleImplements = function(hook) {
var implementations = [];
for (var module in jDrupal.modules) {
if (jDrupal.modules.hasOwnProperty(module)) {
if (jDrupal.functionExists(module + '_' + hook)) {
implementations.push(module);
}
}
}
return implementations.length ? implementations : false;
};
/**
* Given a module name and a hook name, this will invoke that module's hook and return the results of the invocation.
* Any additional arguments will be sent along to the hook.
* @param {String} module
* @param {String} hook
* @return {*}
*/
jDrupal.moduleInvoke = function(module, hook) {
if (!jDrupal.moduleLoad(module)) { return; }
var name = module + '_' + hook;
if (!jDrupal.functionExists(name)) { return; }
// Get the hook function, then remove the module name and hook from the
// arguments. Then if there are no arguments, just call the hook directly,
// otherwise call the hook and pass along all the arguments.
var fn = window[name];
var module_arguments = Array.prototype.slice.call(arguments);
module_arguments.splice(0, 2);
if (Object.getOwnPropertyNames(module_arguments).length == 0) { return fn(); }
else { return fn.apply(null, module_arguments); }
};
/**
* Given a hook name, this will invoke all modules that implement the hook. Any additional arguments will be sent along
* to each of the hooks.
* @param {String} hook
* @return {Promise}
*/
jDrupal.moduleInvokeAll = function(hook) {
var promises = [];
// Copy the arguments and remove the hook name from the first index so the rest can be passed along to the hook.
var module_arguments = Array.prototype.slice.call(arguments);
module_arguments.splice(0, 1);
// Figure out which modules are implementing this hook.
var modules = [];
for (var module in jDrupal.modules) {
if (!jDrupal.modules.hasOwnProperty(module)) { continue; }
if (!jDrupal.functionExists(module + '_' + hook)) { continue; }
modules.push(module);
}
if (jDrupal.isEmpty(modules)) { return Promise.resolve(); }
for (var i = 0; i < modules.length; i++) {
// If there are no arguments, just call the hook directly, otherwise call the hook and pass along all the arguments.
if (module_arguments.length == 0) {
promises.push(jDrupal.moduleInvoke(modules[i], hook));
}
else {
// Place the module name and hook name on the front of the arguments.
module_arguments.unshift(modules[i], hook);
promises.push(jDrupal.moduleInvoke.apply(null, module_arguments));
module_arguments.splice(0, 2);
}
}
return Promise.all(promises);
};
/**
* Given a module name, this will return the module inside jDrupal.modules, or
* false if it fails to find it.
* @param {String} name
* @return {Object|Boolean}
*/
jDrupal.moduleLoad = function(name) {
return jDrupal.modules[name] ? jDrupal.modules[name] : false;
};
/**
* Returns all active module JSON objects.
* @returns {Object}
*/
jDrupal.modulesLoad = function() { return jDrupal.modules; };
(function(send) {
/**
* Adds a pre process hook to all xhr request, and then continues with the call as usual.
* @param {*} data
*/
XMLHttpRequest.prototype.send = function(data) {
var self = this;
var alters = jDrupal.moduleInvokeAll('rest_pre_process', this, data);
if (!alters) { send.call(this, data); }
else { alters.then(function() { send.call(self, data); }); }
};
})(XMLHttpRequest.prototype.send);
/**
* Given a XHR request, this will parse and return the JSON object from the response.
* @param req {XMLHttpRequest}
*/
jDrupal.getResultFromRequest = function(req) {
return JSON.parse(typeof req.responseText !== 'undefined' ? req.responseText : req.response);
};
/**
* Gets the X-CSRF-Token from Drupal.
* @returns {Promise}
*/
jDrupal.token = function() {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'system',
resource: 'token'
};
req.open('GET', jDrupal.restPath() + 'session/token');
req.onload = function() {
if (req.status == 200) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { resolve(req.response); }
else { invoke.then(resolve(req.response));}
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send();
});
};
/**
* Connects to Drupal and sets the currentUser object.
* @returns {Promise}
*/
jDrupal.connect = function() {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'system',
resource: 'connect'
};
req.open('GET', jDrupal.restPath() + 'jdrupal/connect?_format=json');
var connected = function() {
jDrupal.connected = true;
var result = JSON.parse(typeof req.responseText !== 'undefined' ? req.responseText : req.response);
if (result.uid == 0) {
jDrupal.setCurrentUser(jDrupal.userDefaults());
resolve(result);
}
else {
jDrupal.userLoad(result.uid).then(function(account) {
jDrupal.setCurrentUser(account);
resolve(result);
});
}
};
req.onload = function() {
if (req.status != 200) { reject(req); return; }
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { connected(); }
else { invoke.then(connected); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send();
});
};
/**
* Logs into Drupal, then makes a jDrupal.connect() call to properly set the currentUser object.
* @param {String} name
* @param {String} pass
* @returns {Promise}
*/
jDrupal.userLogin = function(name, pass) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'user',
resource: 'login'
};
req.open('POST', jDrupal.restPath() + 'user/login?_format=json');
req.setRequestHeader('Content-type', 'application/json');
var connected = function() { jDrupal.connect().then(resolve); };
req.onload = function() {
if (req.status == 200) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { connected(); }
else { invoke.then(connected); }
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send(JSON.stringify({
name: name,
pass: pass
}));
});
};
/**
* Logs out of Drupal, clears the currentUser object, then performs a jDrupal.connect() to properly set the currentUser
* object.
* @returns {Promise}
*/
jDrupal.userLogout = function() {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'user',
resource: 'logout'
};
req.open('GET', jDrupal.restPath() + 'user/logout');
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var connected = function() {
jDrupal.setCurrentUser(jDrupal.userDefaults());
jDrupal.connect().then(resolve);
};
req.onload = function() {
if (req.status == 200 || req.status == 303) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { connected(); }
else { invoke.then(connected); }
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send();
});
};
/**
* ENTITY PROXY FUNCTIONS
*/
/**
* Given an entity type and id, this will attempt to load the entity.
* @param {String} entityType
* @param {Number} entityID
* @returns {Promise}
*/
jDrupal.entityLoad = function(entityType, entityID) {
var entity = new this[this.ucfirst(entityType)](entityID);
return entity.load();
};
/**
* Given a comment id, this will attempt to load the comment.
* @param {Number} cid
* @returns {Promise}
*/
jDrupal.commentLoad = function(cid) { return this.entityLoad('comment', cid); };
/**
* Given a node id, this will attempt to load the node.
* @param {Number} nid
* @returns {Promise}
*/
jDrupal.nodeLoad = function(nid) { return this.entityLoad('node', nid); };
/**
* Given a user id, this will attempt to load the account.
* @param {Number} uid
* @returns {Promise}
*/
jDrupal.userLoad = function(uid) { return this.entityLoad('user', uid); };
/**
* Registers a new user.
* @param {String} name
* @param {String} pass
* @param {String} mail
* @returns {Promise}
*/
jDrupal.userRegister = function(name, pass, mail) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'user',
resource: 'register'
};
req.open('POST', jDrupal.restPath() + 'user/register?_format=json');
req.setRequestHeader('Content-type', 'application/json');
var connected = function() {
jDrupal.connect().then(resolve);
};
req.onload = function() {
if (req.status == 200) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { connected(); }
else { invoke.then(connected); }
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send(JSON.stringify({
name: {value : name},
pass: {value: pass},
mail: {value: mail}
}));
});
};
/**
* The Views constructor.
* @param {String} path The path to the Views REST Export in Drupal.
* @constructor
*/
jDrupal.Views = function(path) {
this.path = path;
this.results = null;
};
/**
* Returns the path to the rest export.
* @returns {String}
*/
jDrupal.Views.prototype.getPath = function() {
return this.path;
};
/**
* Returns the results, if any.
* @returns {*}
*/
jDrupal.Views.prototype.getResults = function() {
return this.results;
};
/**
* Retrieves the Views' results from the Drupal site's rest export.
* @returns {Promise}
*/
jDrupal.Views.prototype.getView = function() {
var self = this;
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.dg = {
service: 'views',
resource: null
};
req.open('GET', jDrupal.restPath() + self.getPath());
var loaded = function() {
self.results = JSON.parse(req.response);
resolve();
};
req.onload = function() {
if (req.status == 200) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { loaded(); }
else { invoke.then(loaded); }
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send();
});
};
/**
* Loads a view and fetches its results from the Drupal site.
* @param {String} path
*/
jDrupal.viewsLoad = function(path) {
return new Promise(function(resolve, reject) {
var view = new jDrupal.Views(path);
view.getView().then(function() {
resolve(view);
});
});
};
/**
* Given a entity type, bundle and id, this Creates a new jDrupal Entity object.
* @param entityType
* @param bundle
* @param id
* @constructor
*/
jDrupal.Entity = function(entityType, bundle, id) {
// @TODO Allow an entity object to be passed in.
this.entity = null;
// @TODO these flat values need to be turned into arrays, e.g. [ { value: 'foo'} ]
this.bundle = bundle;
this.entityID = id;
this.entityKeys = {};
};
/**
*
* @param prop
* @param delta
* @returns {*}
*/
jDrupal.Entity.prototype.get = function(prop, delta) {
if (!this.entity || typeof this.entity[prop] === 'undefined') { return null; }
return typeof delta !== 'undefined' ? this.entity[prop][delta] : this.entity[prop];
};
/**
*
* @param prop
* @param delta
* @param val
*/
jDrupal.Entity.prototype.set = function(prop, delta, val) {
if (this.entity) {
if (typeof delta !== 'undefined' && typeof this.entity[prop] !== 'undefined') {
this.entity[prop][delta] = val;
}
else { this.entity[prop] = val; }
}
};
/**
*
* @param key
* @returns {null}
*/
jDrupal.Entity.prototype.getEntityKey = function(key) {
return typeof this.entityKeys[key] !== 'undefined' ?
this.entityKeys[key] : null;
};
/**
*
* @returns {*}
*/
jDrupal.Entity.prototype.getEntityType = function() {
return this.entityKeys['type'];
};
/**
*
* @returns {*}
*/
jDrupal.Entity.prototype.getBundle = function() {
var bundle = this.getEntityKey('bundle');
return typeof this.entity[bundle] !== 'undefined' ?
this.entity[bundle][0].target_id : null;
};
/**
*
* @returns {null}
*/
jDrupal.Entity.prototype.id = function() {
var id = this.getEntityKey('id');
return typeof this.entity[id] !== 'undefined' ?
this.entity[id][0].value : null;
};
/**
*
* @returns {*}
*/
jDrupal.Entity.prototype.language = function() {
return this.entity.langcode[0].value;
};
/**
*
* @returns {boolean}
*/
jDrupal.Entity.prototype.isNew = function() {
return !this.id();
};
/**
*
* @returns {null}
*/
jDrupal.Entity.prototype.label = function() {
var label = this.getEntityKey('label');
return typeof this.entity[label] !== 'undefined' ?
this.entity[label][0].value : null;
};
/**
* @returns {String}
*/
jDrupal.Entity.prototype.stringify = function() {
return JSON.stringify(this.entity);
};
/**
* ENTITY LOADING...
*/
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.preLoad = function(options) {
return new Promise(function(resolve, reject) {
resolve();
});
};
/**
*
* @returns {Promise}
*/
jDrupal.Entity.prototype.load = function() {
try {
var _entity = this;
var entityType = _entity.getEntityType();
return new Promise(function(resolve, reject) {
_entity.preLoad().then(function() {
var path = jDrupal.restPath() +
entityType + '/' + _entity.id() + '?_format=json';
var req = new XMLHttpRequest();
req.dg = {
service: entityType,
resource: 'retrieve'
};
req.open('GET', path);
var loaded = function() {
_entity.entity = JSON.parse(req.response);
_entity.postLoad(req).then(function() {
resolve(_entity);
});
};
req.onload = function() {
if (req.status == 200) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { loaded(); }
else { invoke.then(loaded); }
}
else { reject(req); }
};
req.onerror = function() { reject(Error("Network Error")); };
req.send();
});
});
}
catch (error) {
console.log('jDrupal.Entity.load - ' + error);
}
};
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.postLoad = function(options) {
return new Promise(function(resolve, reject) {
resolve();
});
};
/**
* ENTITY SAVING...
*/
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.preSave = function(options) {
return new Promise(function(resolve, reject) {
resolve();
});
};
/**
*
* @returns {Promise}
*/
jDrupal.Entity.prototype.save = function() {
var _entity = this;
return new Promise(function(resolve, reject) {
_entity.preSave().then(function() {
jDrupal.token().then(function(token) {
var entityType = _entity.getEntityType();
var method = null;
var resource = null;
var path = null;
var isNew = _entity.isNew();
if (isNew) {
method = 'POST';
resource = 'create';
path = entityType;
}
else {
method = 'PATCH';
resource = 'update';
path = entityType + '/' + _entity.id();
}
path += '?_format=json';
var req = new XMLHttpRequest();
req.dg = {
service: entityType,
resource: resource
};
req.open(method, jDrupal.restPath() + path);
req.setRequestHeader('Content-type', 'application/json');
req.setRequestHeader('X-CSRF-Token', token);
req.onload = function() {
_entity.postSave(req).then(function() {
if (
(method == 'POST' && req.status == 201) ||
(method == 'PATCH' && req.status == 204) ||
req.status == 200
) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { resolve(req); }
else { invoke.then(resolve(req));}
}
else { reject(req); }
});
};
req.onerror = function() { reject(Error("Network Error")); };
req.send(_entity.stringify());
});
});
});
};
/**
*
* @param xhr
* @returns {Promise}
*/
jDrupal.Entity.prototype.postSave = function(xhr) {
var self = this;
return new Promise(function(resolve, reject) {
// For new entities, grab their id from the Location response header.
if (self.isNew() && xhr.getResponseHeader('Location')) {
var parts = xhr.getResponseHeader('Location').split('/');
var entityID =
self.entity[self.getEntityKey('id')] = [ {
value: parts[parts.length - 1]
}];
}
resolve();
});
};
/**
* ENTITY DELETING...
*/
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.preDelete = function(options) {
return new Promise(function(resolve, reject) {
resolve();
});
};
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.delete = function(options) {
// Set aside "this" entity.
var _entity = this;
return new Promise(function(resolve, reject) {
_entity.preDelete().then(function() {
jDrupal.token().then(function(token) {
var entityType = _entity.getEntityType();
var path = jDrupal.restPath() + entityType + '/' + _entity.id();
var data = {};
data[_entity.getEntityKey('bundle')] = [ {
target_id: _entity.getBundle()
}];
var req = new XMLHttpRequest();
req.dg = {
service: entityType,
resource: 'delete'
};
req.open('DELETE', path);
req.setRequestHeader('Content-type', 'application/json');
req.setRequestHeader('X-CSRF-Token', token);
req.onload = function() {
_entity.postDelete(req).then(function() {
if (req.status == 204) {
var invoke = jDrupal.moduleInvokeAll('rest_post_process', req);
if (!invoke) { resolve(req); }
else { invoke.then(resolve(req));}
}
else { reject(req); }
});
};
req.onerror = function() { reject(Error("Network Error")); };
req.send(JSON.stringify(data));
});
});
});
};
/**
*
* @param options
* @returns {Promise}
*/
jDrupal.Entity.prototype.postDelete = function(options) {
var self = this;
return new Promise(function(resolve, reject) {
self.entity = null;
resolve();
});
};
/**
* HELPERS
*/
/**
*
* @param obj
* @param entityID_or_entity
*/
jDrupal.entityConstructorPrep = function(obj, entityID_or_entity) {
if (!entityID_or_entity) { }
else if (typeof entityID_or_entity === 'object') {
obj.entity = entityID_or_entity;
}
else {
var id = obj.getEntityKey('id');
var entity = {};
entity[id]= [ { value: entityID_or_entity } ];
obj.entity = entity;
}
};
// @see https://api.drupal.org/api/drupal/core!modules!comment!src!Entity!Comment.php/class/Comment/8
/**
* Given a comment id or JSON object, this Creates a new jDrupal Comment object.
* @param {Number|Object} cid_or_comment
* @constructor
*/
jDrupal.Comment = function(cid_or_comment) {
// Set the entity keys.
this.entityKeys['type'] = 'comment';
this.entityKeys['bundle'] = 'comment_type';
this.entityKeys['id'] = 'cid';
this.entityKeys['label'] = 'subject';
// Prep the entity.
jDrupal.entityConstructorPrep(this, cid_or_comment);
};
/**
* Extend the entity prototype.
* @type {jDrupal.Entity}
*/
jDrupal.Comment.prototype = new jDrupal.Entity;