-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackbone.drupal.js
532 lines (458 loc) · 12 KB
/
backbone.drupal.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
/**
* @file
* Integration with Drupal Services and Backbone.
*/
(function (Backbone) {
"use strict";
Backbone.Drupal = {};
Backbone.Drupal.Model = {};
Backbone.Drupal.Collection = {};
/**
* The user session.
*
* This should be bound to the app as a singleton.
*
* The current user model can be accessed via session.user.
*/
Backbone.Drupal.Model.Session = Backbone.Model.extend({
defaults: {
loggedIn: false
},
/**
* @inheritdoc
*/
initialize: function () {
this.user = new Backbone.Drupal.Model.User({});
},
/**
* Returns whether the current user is logged in.
*
* @return {bool}
* True if the user is logged in, false if not.
*/
loggedIn: function () {
return this.get('loggedIn');
},
/**
* Logs a user in.
*
* @param {string} username
* The username.
* @param {string} password
* The password.
*
* @return {jQuery.Deferred}
* A jQuery promise that will resolve the user model.
*/
login: function (username, password) {
var self = this;
var deferred = Backbone.$.Deferred();
// User is already logged in.
if (this.loggedIn()) {
return deferred.resolve(this.user).promise();
}
this.doPost('/system/connect').done(function (data) {
self.set('loggedIn', true);
// If we are already logged in, there's nothing to do.
if (data.user.uid != 0) {
self.user.set(data.user);
deferred.resolve(self.user);
}
// Perform an actual login.
else {
self.doPost('/user/login', {username: username, password: password})
.done(function (data) {
setCsrfToken(data.token);
self.user.set(data.user);
deferred.resolve(self.user);
});
}
});
return deferred.promise();
},
/**
* Logs a user out.
*
* @return {jQuery.Deferred}
* A jQuery promise that will resolve to the logout request.
*/
logout: function () {
var self = this;
return this.doPost('/user/logout')
.done(function (data) {
resetCsrfToken();
self.set('loggedIn', false);
})
.promise();
},
/**
* Performs a POST request.
*
* @param {string} postUrl
* The URL to POST to.
* @param {object} postData
* Data to POST.
*
* @return {jqXHR}
* A jQuery ajax object.
*/
doPost: function (postUrl, postData) {
// We intentionally set this to read, and then override it by setting type
// to POST. This stops Backbone from messing with out request.
return this.sync('read', this, {
type: 'POST',
url: postUrl,
data: postData ? JSON.stringify(postData) : null,
contentType: 'application/json'
});
}
});
/**
* Base model for Drupal entities.
*/
Backbone.Drupal.Model.Entity = Backbone.Model.extend({
/**
* @inheritdoc
*/
initialize: function() {
this.idAttribute = this.constructor.idKey;
},
/**
* Returns the label of the entity.
*
* @return {string}
* The entity label.
*/
label: function () {
return this.get(this.constructor.labelKey);
},
/**
* Returns the bundle of the entity.
*
* @return {string}
* The bundle value, or null if the entity does not have a bundle.
*/
bundle: function () {
return this.constructor.bundleKey === null ? null : this.get(this.constructor.bundleKey);
},
/**
* @inheritdoc
*/
url: function () {
var root = '/' + this.constructor.entityType;
if (this.isNew()) {
return root;
}
return root + '/' + encodeURIComponent(this.get(this.constructor.idKey));
},
/**
* @inheritdoc
*/
toJSON: function (options) {
var attributes = Backbone.Model.prototype.toJSON.call(this, options);
_.each(this.constructor.integerFields, function (key) {
if (typeof attributes[key] !== 'undefined') {
attributes[key] = this.convertInteger(attributes[key]);
}
}, this);
// Convert boolean fields.
_.each(this.constructor.booleanFields, function (key) {
if (typeof attributes[key] !== 'undefined') {
attributes[key] = this.convertBoolOutput(attributes[key]);
}
}, this);
// Save a bit of bandwidth.
delete attributes.rdf_mapping;
return attributes;
},
/**
* @inheritdoc
*/
set: function(key, val, options) {
if (key == null) {
return this;
}
// Handle both `"key", value` and `{key: value}` -style arguments.
var attrs;
if (typeof key === 'object') {
attrs = key;
options = val;
}
else {
(attrs = {})[key] = val;
}
attrs = this.cleanInput(attrs);
return Backbone.Model.prototype.set.call(this, attrs, options);
},
/**
* Cleans input values.
*
* @param {object} values
* A value map.
*
* @return {object}
* A cleaned value map.
*/
cleanInput: function (values) {
_.each(this.constructor.integerFields, function (key) {
if (typeof values[key] !== 'undefined') {
values[key] = this.convertInteger(values[key]);
}
}, this);
// Convert boolean fields.
_.each(this.constructor.booleanFields, function (key) {
if (typeof values[key] !== 'undefined') {
values[key] = this.convertBoolInput(values[key]);
}
}, this);
if (typeof values[this.constructor.idKey] !== 'undefined') {
values[this.constructor.idKey] = this.convertInteger(values[this.constructor.idKey]);
}
return values;
},
/**
* Converts boolean values that come from Services.
*
* @param {mixed} value
* The value to convert.
*
* @return {bool}
* The converted value.
*/
convertBoolInput: function (value) {
if (typeof value === 'boolean') {
return value;
}
value = parseInt(value);
return isNaN(value) ? false : value > 0;
},
/**
* Converts boolean values to values Services can handle.
*
* @see http://drupal.org/node/1511662 and http://drupal.org/node/1561292
*
* @param {mixed} value
* The value to convert.
*
* @return {true|null}
* The converted value.
*/
convertBoolOutput: function (value) {
if (typeof value === 'number') {
return value > 0 ? true : null;
}
if (typeof value === 'boolean') {
return value ? true : null;
}
if (value === '1' || value === 'true') {
return true;
}
return null;
},
/**
* Converts a value to an integer.
*
* @param {*} value
* The value to convert.
*
* @return {integer}
* The converted value.
*/
convertInteger: function (value) {
if (typeof value === 'boolean') {
return value ? 1 : 0;
}
value = parseInt(value);
return isNaN(value) ? 0 : value;
}
},
{
idKey: null,
entityType: null,
bundleKey: null,
labelKey: null,
booleanFields: [],
integerFields: [],
});
/**
* File model.
*/
Backbone.Drupal.Model.File = Backbone.Drupal.Model.Entity.extend({
fileContents: 0,
imageStyles: 1,
/**
* @inheritdoc
*/
url: function () {
var url = Backbone.Drupal.Model.Entity.prototype.url.call(this);
if (this.isNew()) {
return url;
}
// Don't get the file contents.
return url + '?file_contents=' + this.convertInteger(this.fileContents) + '&image_styles=' + this.convertInteger(this.imageStyles);
},
},
{
idKey: 'fid',
entityType: 'file',
bundleKey: 'type',
labelKey: 'filename',
booleanFields: [],
integerFields: ['filesize', 'status', 'timestamp', 'uid'],
});
/**
* Node model.
*/
Backbone.Drupal.Model.Node = Backbone.Drupal.Model.Entity.extend({}, {
idKey: 'nid',
entityType: 'node',
bundleKey: 'type',
labelKey: 'title',
booleanFields: ['status', 'sticky', 'promote'],
integerFields: [
'changed',
'cid',
'comment',
'comment_count',
'created',
'last_comment_timestamp',
'last_comment_uid',
'revision_timestamp',
'revision_uid',
'tnid',
'translate',
'uid',
'vid'
]
});
/**
* Taxonomy term model.
*/
Backbone.Drupal.Model.TaxonomyTerm = Backbone.Drupal.Model.Entity.extend({}, {
idKey: 'tid',
entityType: 'taxonomy_term',
bundleKey: 'vocabulary_machine_name',
labelKey: 'name',
integerFields: ['vid', 'weight']
});
/**
* Taxonomy vocabulary model.
*/
Backbone.Drupal.Model.TaxonomyVocabulary = Backbone.Drupal.Model.Entity.extend({}, {
idKey: 'vid',
entityType: 'taxonomy_vocabulary',
labelKey: 'name',
integerFields: ['hierarchy', 'weight']
});
/**
* User model.
*/
Backbone.Drupal.Model.User = Backbone.Drupal.Model.Entity.extend({}, {
idKey: 'uid',
entityType: 'user',
labelKey: 'name',
integerFields: ['access', 'created', 'login', 'status']
});
/**
* Base class for entity collections.
*/
Backbone.Drupal.Collection.Entity = Backbone.Collection.extend({
/**
* @inheritdoc
*/
url: function () {
return '/' + this.model.entityType;
},
});
/**
* File collections.
*/
Backbone.Drupal.Collection.File = Backbone.Drupal.Collection.Entity.extend({
model: Backbone.Drupal.Model.File
});
/**
* Node collections.
*/
Backbone.Drupal.Collection.Node = Backbone.Drupal.Collection.Entity.extend({
model: Backbone.Drupal.Model.Node
});
/**
* Taxonomy term collections.
*/
Backbone.Drupal.Collection.TaxonomyTerm = Backbone.Drupal.Collection.Entity.extend({
model: Backbone.Drupal.Model.TaxonomyTerm
});
/**
* Taxonomy vocabulary collections.
*/
Backbone.Drupal.Collection.TaxonomyVocabulary = Backbone.Drupal.Collection.Entity.extend({
model: Backbone.Drupal.Model.TaxonomyVocabulary
});
/**
* User collections.
*/
Backbone.Drupal.Collection.User = Backbone.Drupal.Collection.Entity.extend({
model: Backbone.Drupal.Model.User
});
var _sync = Backbone.sync;
/**
* Overrides Backbone.sync to ensure that tokens are added to all requests.
*/
Backbone.sync = function (method, model, options) {
options = options || {};
options.url = options.url || model.url();
options.url = Backbone.Drupal.appRoot + options.url;
options.xhrFields = options.xhrFields || {};
options.xhrFields.withCredentials = true;
return getCsrfToken().then(function (token) {
// Set the CSRF token, making sure that any other beforeSend methods are
// honored.
var _beforeSend = options.beforeSend;
options.beforeSend = function (xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
if (_beforeSend) {
_beforeSend(xhr);
}
};
return _sync(method, model, options);
});
};
/**
* Returns the CSRF token.
*
* @return {jQuery.Deferred}
* A jQuery promise that will resolve the token.
*/
function getCsrfToken () {
var self = this;
if (!getCsrfToken.token) {
return Backbone.$.ajax({
url: Backbone.Drupal.appRoot + '/user/token',
type: 'POST',
contentType: 'application/json',
xhrFields: {withCredentials: true}
})
.then(function (data) {
setCsrfToken(data.token);
return data.token;
})
.promise();
}
return Backbone.$.Deferred().resolve(getCsrfToken.token).promise();
}
/**
* Sets the CSRF token.
*
* @param {token} token
* The CSRF token.
*/
function setCsrfToken (token) {
getCsrfToken.token = token;
}
/**
* Resets the CSRF token.
*/
function resetCsrfToken () {
getCsrfToken.token = false;
}
})(Backbone, _);