-
Notifications
You must be signed in to change notification settings - Fork 36
/
resourceApi.ts
805 lines (751 loc) · 25.6 KB
/
resourceApi.ts
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
// @ts-nocheck
import _ from 'underscore';
import { hijackBackboneAjax } from '../../utils/ajax/backboneAjax';
import { Http } from '../../utils/ajax/definitions';
import { removeKey } from '../../utils/utils';
import { assert } from '../Errors/assert';
import { softFail } from '../Errors/Crash';
import { Backbone } from './backbone';
import { attachBusinessRules } from './businessRules';
import { backboneFieldSeparator } from './helpers';
import {
getFieldsToNotClone,
getResourceApiUrl,
getResourceViewUrl,
resourceEvents,
resourceFromUrl,
} from './resource';
import { initializeResource } from './scoping';
import { specialFields } from './serializers';
// REFACTOR: remove @ts-nocheck
function eventHandlerForToOne(related, field) {
return function (event) {
const args = _.toArray(arguments);
switch (event) {
case 'saverequired': {
this.handleChanged();
this.trigger.apply(this, args);
return;
}
case 'change:id': {
this.set(field.name, related.url());
return;
}
case 'changing': {
this.trigger.apply(this, args);
return;
}
}
// Pass change:field events up the tree, updating fields with dot notation
const match = /^r?(change):(.*)$/.exec(event);
if (match) {
args[0] = `r${match[1]}:${field.name.toLowerCase()}.${match[2]}`;
this.trigger.apply(this, args);
}
};
}
function eventHandlerForToMany(_related, field) {
return function (event) {
const args = _.toArray(arguments);
switch (event) {
case 'changing': {
this.trigger.apply(this, args);
break;
}
case 'saverequired': {
this.handleChanged();
this.trigger.apply(this, args);
break;
}
case 'add':
case 'remove': {
// Annotate add and remove events with the field in which they occurred
args[0] = `${event}:${field.name.toLowerCase()}`;
this.trigger.apply(this, args);
break;
}
}
};
}
// Always returns a resource
const maybeMakeResource = (value, relatedTable) =>
value instanceof ResourceBase
? value
: new relatedTable.Resource(value, { parse: true });
export const ResourceBase = Backbone.Model.extend({
__name__: 'ResourceBase',
populated: false, // Indicates if this resource has data
_fetch: null, // Stores reference to the ajax deferred while the resource is being fetched
needsSaved: false, // Set when a local field is changed
_save: null, // Stores reference to the ajax deferred while the resource is being saved
/**
* Returns true if the resource is being fetched and saved from Backbone
* More specifically, returns true while this resource holds a reference
* to Backbone's save() and fetch() in _save and _fetch
*/
isBeingInitialized() {
return this._save !== null || this._fetch !== null;
},
constructor() {
this.specifyTable = this.constructor.specifyTable;
this.dependentResources = {}; // References to related objects referred to by field in this resource
Reflect.apply(Backbone.Model, this, arguments); // TEST: check if this is necessary
},
initialize(attributes, options) {
this.noBusinessRules = options && options.noBusinessRules;
this.noValidation = options && options.noValidation;
this.createdBy = options && options.createdBy;
/*
* If initialized with some attributes that include a resource_uri,
* assume that represents all the fields for the resource
*/
if (attributes && _(attributes).has('resource_uri')) this.populated = true;
/*
* The resource needs to be saved if any of its fields change
* unless they change because the resource is being fetched
* or updated during a save
*/
this.on('change', function () {
if (!this._fetch && !this._save) {
this.handleChanged();
this.trigger('saverequired');
}
});
if (!this.noBusinessRules) attachBusinessRules(this);
if (this.isNew()) initializeResource(this);
/*
* Business rules may set some fields on resource creation
* Those default values should not trigger unload protect
*/
this.needsSaved = false;
},
/*
* This is encapsulated into a separate function so that can set a
* breakpoint in a single place
*/
handleChanged() {
this.needsSaved = true;
},
async clone(cloneAll = false, isBulkCarry = false) {
const self = this;
const exemptFields = getFieldsToNotClone(
this.specifyTable,
cloneAll,
isBulkCarry
).map((fieldName) => fieldName.toLowerCase());
const newResource = new this.constructor(
removeKey(this.attributes, ...specialFields, ...exemptFields),
{ createdBy: 'clone' }
);
newResource.needsSaved = self.needsSaved;
await Promise.all(
Object.entries(self.dependentResources).map(
async ([fieldName, related]) => {
if (exemptFields.includes(fieldName)) return;
const field = self.specifyTable.getField(fieldName);
switch (field.type) {
case 'many-to-one': {
/*
* Many-to-one wouldn't ordinarily be dependent, but
* this is the case for paleocontext. really more like
* a one-to-one.
*/
newResource.set(fieldName, await related?.clone(cloneAll));
break;
}
case 'one-to-many': {
await newResource
.rget(fieldName)
.then(async (newCollection) =>
Promise.all(
related.models.map(async (resource) =>
newCollection.add(await resource?.clone(cloneAll))
)
)
);
break;
}
case 'zero-to-one': {
newResource.set(fieldName, await related?.clone(cloneAll));
break;
}
default: {
throw new Error('unhandled relationship type');
}
}
}
)
);
return newResource;
},
url() {
return getResourceApiUrl(this.specifyTable.name, this.id);
},
viewUrl() {
// Returns the url for viewing this resource in the UI
if (!_.isNumber(this.id))
softFail(new Error('viewUrl called on resource without id'), this);
return getResourceViewUrl(this.specifyTable.name, this.id);
},
get(attribute) {
if (
attribute.toLowerCase() === this.specifyTable.idField.name.toLowerCase()
)
return this.id;
// Case insensitive
return Backbone.Model.prototype.get.call(this, attribute.toLowerCase());
},
storeDependent(field, related) {
assert(field.isDependent());
const setter =
field.type === 'one-to-many'
? '_setDependentToMany'
: '_setDependentToOne';
this[setter](field, related);
},
_setDependentToOne(field, related) {
const oldRelated = this.dependentResources[field.name.toLowerCase()];
if (!related) {
if (oldRelated) {
oldRelated.off('all', null, this);
this.trigger('saverequired');
}
this.dependentResources[field.name.toLowerCase()] = null;
return;
}
if (oldRelated && oldRelated.cid === related.cid) return;
oldRelated && oldRelated.off('all', null, this);
related.on('all', eventHandlerForToOne(related, field), this);
related.parent = this; // REFACTOR: this doesn't belong here
switch (field.type) {
case 'one-to-one':
case 'many-to-one': {
this.dependentResources[field.name.toLowerCase()] = related;
break;
}
case 'zero-to-one': {
this.dependentResources[field.name.toLowerCase()] = related;
related.set(field.otherSideName, this.url()); // REFACTOR: this logic belongs somewhere else. up probably
break;
}
default: {
throw new Error(
`setDependentToOne: unhandled field type: ${field.type}`
);
}
}
},
_setDependentToMany(field, toMany) {
const oldToMany = this.dependentResources[field.name.toLowerCase()];
oldToMany && oldToMany.off('all', null, this);
// Cache it and set up event handlers
this.dependentResources[field.name.toLowerCase()] = toMany;
toMany.on('all', eventHandlerForToMany(toMany, field), this);
},
// Separate name to simplify typing
bulkSet(attributes, options) {
return this.set(attributes, options);
},
set(key, value, options) {
// This may get called with "null" or "undefined"
const newValue = value ?? undefined;
const oldValue =
typeof key === 'string'
? this.attributes[key.toLowerCase()] ??
this.dependentResources[key.toLowerCase()] ??
undefined
: undefined;
// Don't needlessly trigger unload protect if value didn't change
if (
typeof key === 'string' &&
typeof (oldValue ?? '') !== 'object' &&
typeof (newValue ?? '') !== 'object'
) {
if (oldValue === newValue) return this;
else if (
/*
* Don't trigger unload protect if:
* - value didn't change
* - value changed from string to number (back-end sends
* decimal numeric fields as string. Front-end converts
* those to numbers)
* - value was trimmed
*
* Using "==" instead of "===" because of
* https://github.com/specify/specify7/issues/2976
* REFACTOR: this logic should be moved to this.parse()
* TEST: add test for "5A" case
* TEST: add test for "38.06020000" and 38.0602 case
*/
oldValue?.toString() == newValue?.toString().trim()
)
options ??= { silent: true };
}
// Make the keys case insensitive
const attributes = {};
if (_.isObject(key) || key == null) {
/*
* In the two argument case, so
* "key" is actually an object mapping keys to values
*/
_(key).each((value, key) => {
attributes[key.toLowerCase()] = value;
});
// And the options are actually in "value" argument
options = value;
} else {
// Three argument case
attributes[key.toLowerCase()] = value;
}
/*
* Need to set the id right away if we have it because
* relationships depend on it
*/
if ('id' in attributes) {
attributes.id = attributes.id && Number.parseInt(attributes.id);
this.id = attributes.id;
}
const adjustedAttributes = _.reduce(
attributes,
(accumulator, value, fieldName) => {
const [newFieldName, newValue] = this._handleField(value, fieldName);
return _.isUndefined(newValue)
? accumulator
: Object.assign(accumulator, { [newFieldName]: newValue });
},
{}
);
const result = Backbone.Model.prototype.set.call(
this,
adjustedAttributes,
options
);
/*
* Unlike "change", if changing multiple fields at once, this
* triggers only once after all changes
*/
this.trigger('changed');
return result;
},
_handleField(value, fieldName) {
if (fieldName === '_tablename') return ['_tablename', undefined];
if (_(['id', 'resource_uri', 'recordset_info']).contains(fieldName))
return [fieldName, value]; // Special fields
const field = this.specifyTable.getField(fieldName);
if (!field) {
console.warn(
`Setting unknown field ${fieldName} on ${this.specifyTable.name}.\n`,
`If this is a virtual field, define it in schemaExtras.ts`,
{ value, resource: this }
);
return [fieldName, value];
}
fieldName = field.name.toLowerCase(); // In case field name is an alias.
if (field.isRelationship) {
value = _.isString(value)
? this._handleUri(value, fieldName)
: typeof value === 'number'
? this._handleUri(
// Back-end sends SpPrincipal.scope as a number, rather than as a URL
getResourceApiUrl(field.table.name, value),
fieldName
)
: this._handleInlineDataOrResource(value, fieldName);
}
return [fieldName, value];
},
_handleInlineDataOrResource(value, fieldName) {
// BUG: check type of value
const field = this.specifyTable.getField(fieldName);
const relatedTable = field.relatedTable;
// BUG: don't do anything for virtual fields
switch (field.type) {
case 'one-to-many': {
// Should we handle passing in an schema.Model.Collection instance here??
const collectionOptions = { related: this, field: field.getReverse() };
if (field.isDependent()) {
const collection = new relatedTable.DependentCollection(
collectionOptions,
value
);
this.storeDependent(field, collection);
} else {
console.warn(
'got unexpected inline data for independent collection field',
{ collection: this, field, value }
);
}
// Because the foreign key is on the other side
this.trigger(`change:${fieldName}`, this);
this.trigger('change', this);
return undefined;
}
case 'many-to-one': {
if (!value) {
/*
* BUG: tighten up this check.
* The FK is null, or not a URI or inlined resource at any rate
*/
field.isDependent() && this.storeDependent(field, null);
return value;
}
const toOne = maybeMakeResource(value, relatedTable);
field.isDependent() && this.storeDependent(field, toOne);
this.trigger(`change:${fieldName}`, this);
this.trigger('change', this);
return toOne.url();
} // The FK as a URI
case 'zero-to-one': {
/*
* This actually a one-to-many where the related collection is only a single resource
* basically a one-to-one from the 'to' side
*/
const oneTo = _.isArray(value)
? value.length === 0
? null
: maybeMakeResource(_.first(value), relatedTable)
: value || null; // In case it was undefined
assert(oneTo == null || oneTo instanceof ResourceBase);
field.isDependent() && this.storeDependent(field, oneTo);
// Because the FK is on the other side
this.trigger(`change:${fieldName}`, this);
this.trigger('change', this);
return undefined;
}
}
if (!field.isVirtual)
softFail('Unhandled setting of relationship field', {
fieldName,
value,
resource: this,
});
return value;
},
_handleUri(value, fieldName) {
const field = this.specifyTable.getField(fieldName);
const oldRelated = this.dependentResources[fieldName];
if (field.isDependent()) {
console.warn(
'expected inline data for dependent field',
fieldName,
'in',
this
);
}
if (oldRelated && field.type === 'many-to-one') {
/*
* Probably should never get here since the presence of an oldRelated
* value implies a dependent field which wouldn't be receiving a URI value
*/
console.warn('unexpected condition');
if (oldRelated.url() !== value) {
// The reference changed
delete this.dependentResources[fieldName];
oldRelated.off('all', null, this);
}
}
return value;
},
/*
* Get the value of the named field where the name may traverse related objects
* using dot notation. if the named field represents a resource or collection,
* then prePop indicates whether to return the named object or the contents of
* the field that represents it
*/
async rget(fieldName, prePop) {
return this.getRelated(fieldName, { prePop });
},
/*
* REFACTOR: remove the need for this
* Like "rget", but returns native promise
*/
async rgetPromise(fieldName, prePop = true, strict = true) {
return (
this.getRelated(fieldName, { prePop, strict })
// GetRelated may return either undefined or null (yuk)
.then((data) => (data === undefined ? null : data))
);
},
// Duplicate definition for purposes of better typing:
async rgetCollection(fieldName) {
return this.getRelated(fieldName, { prePop: true });
},
async getRelated(fieldName, options) {
options ||= {
prePop: false,
noBusinessRules: false,
};
const path = _(fieldName).isArray()
? fieldName
: fieldName.split(backboneFieldSeparator);
// First make sure we actually have this object.
return this.fetch(options)
.then((_this) => _this._rget(path, options))
.then((value) => {
/*
* If the requested value is fetchable, and prePop is true,
* fetch the value, otherwise return the unpopulated resource
* or collection
*/
if (options.prePop) {
if (!value) return value; // Ok if the related resource doesn't exist
else if (typeof value.fetchIfNotPopulated === 'function')
return value.fetchIfNotPopulated();
else if (typeof value.fetch === 'function')
return value.fetch(options);
}
return value;
});
},
async _rget(path, options) {
let fieldName = path[0].toLowerCase();
const field = this.specifyTable.getField(fieldName);
field && (fieldName = field.name.toLowerCase()); // In case fieldName is an alias
let value = this.get(fieldName);
field ||
console.warn(
'accessing unknown field',
fieldName,
'in',
this.specifyTable.name,
'value is',
value
);
/*
* If field represents a value, then return that if we are done,
* otherwise we can't traverse any farther...
*/
if (!field || !field.isRelationship) {
if (path.length > 1) {
softFail('expected related field');
return undefined;
}
return value;
}
const _this = this;
const related = field.relatedTable;
switch (field.type) {
case 'one-to-one':
case 'many-to-one': {
// A foreign key field.
if (!value) return value; // No related object
// Is the related resource cached?
let toOne = this.dependentResources[fieldName];
if (!toOne) {
_(value).isString() || softFail('expected URI, got', value);
toOne = resourceFromUrl(value, {
noBusinessRules: options.noBusinessRules,
});
if (field.isDependent()) {
console.warn('expected dependent resource to be in cache');
this.storeDependent(field, toOne);
}
}
// If we want a field within the related resource then recur
return path.length > 1 ? toOne.rget(_.tail(path)) : toOne;
}
case 'one-to-many': {
if (path.length !== 1) {
throw "can't traverse into a collection using dot notation";
}
// Is the collection cached?
let toMany = this.dependentResources[fieldName];
if (!toMany) {
const collectionOptions = {
field: field.getReverse(),
related: this,
};
if (!field.isDependent()) {
return new related.ToOneCollection(collectionOptions);
}
if (this.isNew()) {
toMany = new related.DependentCollection(collectionOptions, []);
this.storeDependent(field, toMany);
return toMany;
} else {
console.warn('expected dependent resource to be in cache');
const temporaryCollection = new related.ToOneCollection(
collectionOptions
);
return temporaryCollection
.fetch({ limit: 0 })
.then(
() =>
new related.DependentCollection(
collectionOptions,
temporaryCollection.tables
)
)
.then((toMany) => {
_this.storeDependent(field, toMany);
});
}
}
}
case 'zero-to-one': {
/*
* This is like a one-to-many where the many cannot be more than one
* i.e. the current resource is the target of a FK
*/
// Is it already cached?
if (!_.isUndefined(this.dependentResources[fieldName])) {
value = this.dependentResources[fieldName];
if (value == null) return null;
// Recur if we need to traverse more
return path.length === 1 ? value : value.rget(_.tail(path));
}
// If this resource is not yet persisted, the related object can't point to it yet
if (this.isNew()) return undefined; // TEST: this seems iffy
const collection = new related.ToOneCollection({
field: field.getReverse(),
related: this,
limit: 1,
});
// Fetch the collection and pretend like it is a single resource
return collection.fetchIfNotPopulated().then(() => {
const value = collection.isEmpty() ? null : collection.first();
if (field.isDependent()) {
console.warn('expect dependent resource to be in cache');
_this.storeDependent(field, value);
}
if (value == null) return null;
return path.length === 1 ? value : value.rget(_.tail(path));
});
}
default: {
softFail(`unhandled relationship type: ${field.type}`);
throw 'unhandled relationship type';
}
}
},
save({
onSaveConflict: handleSaveConflict,
errorOnAlreadySaving = true,
} = {}) {
const resource = this;
if (resource._save) {
// REFACTOR: instead of erroring on save, just return same promise again
if (errorOnAlreadySaving)
throw new Error('resource is already being saved');
else return resource._save;
}
const didNeedSaved = resource.needsSaved;
resource.needsSaved = false;
// BUG: should do this for dependent resources too
let errorHandled = false;
const save = () =>
Backbone.Model.prototype.save
.apply(resource, [])
.then(() => resource.trigger('saved'));
resource._save =
typeof handleSaveConflict === 'function'
? hijackBackboneAjax([Http.CONFLICT], save, (status) => {
if (status === Http.CONFLICT) {
handleSaveConflict();
errorHandled = true;
}
})
: save();
resource._save
.catch((error) => {
resource._save = null;
resource.needsSaved = didNeedSaved;
didNeedSaved && resource.trigger('saverequired');
if (typeof handleSaveConflict === 'function' && errorHandled)
Object.defineProperty(error, errorHandledBy, {
value: handleSaveConflict,
});
throw error;
})
.then(() => {
resource._save = null;
});
return resource._save.then(() => resource);
},
deleted: false,
async destroy(...args) {
const promise = await Backbone.Model.prototype.destroy.apply(this, ...args);
this.deleted = true;
resourceEvents.trigger('deleted', this);
return promise;
},
toJSON() {
const self = this;
const json = Backbone.Model.prototype.toJSON.apply(self, arguments);
_.each(self.dependentResources, (related, fieldName) => {
const field = self.specifyTable.getField(fieldName);
if (field.type === 'zero-to-one') {
json[fieldName] = related ? [related.toJSON()] : [];
} else {
json[fieldName] = related ? related.toJSON() : null;
}
});
if (typeof this.get('resource_uri') !== 'string')
json._tableName = this.specifyTable.name;
return json;
},
// Caches a reference to Promise so as not to start fetching twice
async fetch(options) {
if (
// If already populated
this.populated ||
// Or if can't be populated by fetching
this.isNew()
)
return this;
else if (this._fetch) return this._fetch;
else
return (this._fetch = hijackBackboneAjax(
options === undefined || options.strict ? undefined : [Http.NOT_FOUND],
() =>
Backbone.Model.prototype.fetch.call(this, options).then(() => {
this._fetch = null;
// BUG: consider doing this.needsSaved=false here
return this;
})
));
},
parse(_resp) {
// Since we are putting in data, the resource in now populated
this.populated = true;
return Reflect.apply(Backbone.Model.prototype.parse, this, arguments);
},
async sync(method, resource, options) {
options ||= {};
if (method === 'delete')
// When deleting we don't send any data so put the version in a header
options.headers = { 'If-Match': resource.get('version') };
return Backbone.sync(method, resource, options);
},
async placeInSameHierarchy(other) {
const self = this;
const myPath = self.specifyTable.getScopingPath();
const otherPath = other.specifyTable.getScopingPath();
if (!myPath || !otherPath) return undefined;
if (myPath.length > otherPath.length) return undefined;
const diff = _(otherPath)
.rest(myPath.length - 1)
.reverse();
// REFACTOR: use mappingPathToString in all places like this
return other.rget(diff.join(backboneFieldSeparator)).then((common) => {
if (common === undefined) return undefined;
self.set(_(diff).last(), common.url());
return common;
});
},
getDependentResource(fieldName) {
return this.dependentResources[fieldName.toLowerCase()];
},
});
export function promiseToXhr(promise) {
promise.done = function (function_) {
return promiseToXhr(promise.then(function_));
};
promise.fail = function (function_) {
return promiseToXhr(promise.then(null, function_));
};
promise.complete = function (function_) {
return promiseToXhr(promise.then(function_, function_));
};
return promise;
}