forked from AleksandrRogov/DynamicsWebApi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamics-web-api.js
More file actions
3552 lines (3001 loc) · 123 KB
/
Copy pathdynamics-web-api.js
File metadata and controls
3552 lines (3001 loc) · 123 KB
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
/*! dynamics-web-api v1.7.5 (c) 2022 Aleksandr Rogov */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("DynamicsWebApi", [], factory);
else if(typeof exports === 'object')
exports["DynamicsWebApi"] = factory();
else
root["DynamicsWebApi"] = factory();
})(self, function() {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 923:
/***/ ((module) => {
var DWA = {
Types: {
ResponseBase: function () {
/// <field name='oDataContext' type='String'>The context URL (see [OData-Protocol]) for the payload.</field>
this.oDataContext = "";
},
Response: function () {
/// <field name='value' type='Object'>Response value returned from the request.</field>
DWA.Types.ResponseBase.call(this);
this.value = {};
},
ReferenceResponse: function () {
/// <field name='id' type='String'>A String representing the GUID value of the record.</field>
/// <field name='collection' type='String'>The name of the Entity Collection that the record belongs to.</field>
DWA.Types.ResponseBase.call(this);
this.id = "";
this.collection = "";
},
MultipleResponse: function () {
/// <field name='oDataNextLink' type='String'>The link to the next page.</field>
/// <field name='oDataCount' type='Number'>The count of the records.</field>
/// <field name='value' type='Array'>The array of the records returned from the request.</field>
DWA.Types.ResponseBase.call(this);
this.oDataNextLink = "";
this.oDataCount = 0;
this.value = [];
},
FetchXmlResponse: function () {
/// <field name='value' type='Array'>The array of the records returned from the request.</field>
/// <field name='pagingInfo' type='Object'>Paging Information</field>
DWA.Types.ResponseBase.call(this);
this.value = [];
this.PagingInfo = {
/// <param name='cookie' type='String'>Paging Cookie</param>
/// <param name='number' type='Number'>Page Number</param>
cookie: "",
page: 0,
nextPage: 1
}
}
},
Prefer: {
/// <field type="String">return=representation</field>
ReturnRepresentation: "return=representation",
Annotations: {
/// <field type="String">Microsoft.Dynamics.CRM.associatednavigationproperty</field>
AssociatedNavigationProperty: 'Microsoft.Dynamics.CRM.associatednavigationproperty',
/// <field type="String">Microsoft.Dynamics.CRM.lookuplogicalname</field>
LookupLogicalName: 'Microsoft.Dynamics.CRM.lookuplogicalname',
/// <field type="String">*</field>
All: '*',
/// <field type="String">OData.Community.Display.V1.FormattedValue</field>
FormattedValue: 'OData.Community.Display.V1.FormattedValue',
/// <field type="String">Microsoft.Dynamics.CRM.fetchxmlpagingcookie</field>
FetchXmlPagingCookie: 'Microsoft.Dynamics.CRM.fetchxmlpagingcookie'
}
}
}
module.exports = DWA;
/***/ }),
/***/ 530:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var DWA = __webpack_require__(923);
var Utility = __webpack_require__(389);
var ErrorHelper = __webpack_require__(535);
var Request = __webpack_require__(67);
//string es6 polyfill
if (!String.prototype.endsWith || !String.prototype.startsWith) {
__webpack_require__(200);
}
/**
* Configuration object for DynamicsWebApi
* @typedef {object} DWAConfig
* @property {string} webApiUrl - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @property {string} impersonate - A String representing a GUID value for the Dynamics 365 system user id.
* @property {string} impersonate - A String representing a URL to Web API (webApiVersion not required if webApiUrl specified) [not used inside of CRM]
* @property {string} impersonateAAD - A String representing a GUID value for the Azure active directory object id.
* @property {Function} onTokenRefresh - A function that is called when a security token needs to be refreshed.
* @property {string} includeAnnotations - Sets Prefer header with value "odata.include-annotations=" and the specified annotation. Annotations provide additional information about lookups, options sets and other complex attribute types.
* @property {string} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {boolean} useEntityNames - Indicates whether to use Entity Logical Names instead of Collection Logical Names.
*/
/**
* Dynamics Web Api Request
* @typedef {Object} DWARequest
* @property {boolean} async - XHR requests only! Indicates whether the requests should be made synchronously or asynchronously. Default value is 'true' (asynchronously).
* @property {string} collection - The name of the Entity Collection or Entity Logical name.
* @property {string} id - A String representing the Primary Key (GUID) of the record.
* @property {Array} select - An Array (of Strings) representing the $select OData System Query Option to control which attributes will be returned.
* @property {Array} expand - An array of Expand Objects (described below the table) representing the $expand OData System Query Option value to control which related records are also returned.
* @property {string} key - A String representing collection record's Primary Key (GUID) or Alternate Key(s).
* @property {string} filter - Use the $filter system query option to set criteria for which entities will be returned.
* @property {number} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {boolean} count - Boolean that sets the $count system query option with a value of true to include a count of entities that match the filter criteria up to 5000 (per page). Do not use $top with $count!
* @property {number} top - Limit the number of results returned by using the $top system query option. Do not use $top with $count!
* @property {Array} orderBy - An Array (of Strings) representing the order in which items are returned using the $orderby system query option. Use the asc or desc suffix to specify ascending or descending order respectively. The default is ascending if the suffix isn't applied.
* @property {string} includeAnnotations - Sets Prefer header with value "odata.include-annotations=" and the specified annotation. Annotations provide additional information about lookups, options sets and other complex attribute types.
* @property {string} ifmatch - Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.
* @property {string} ifnonematch - Sets If-None-Match header value that enables to use conditional retrieval in applicable requests.
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {Object} entity - A JavaScript object with properties corresponding to the logical name of entity attributes (exceptions are lookups and single-valued navigation properties).
* @property {string} impersonate - Impersonates the user. A String representing the GUID value for the Dynamics 365 system user id.
* @property {string} impersonateAAD - Impersonates the user. A String representing the GUID value for the Azure active directory object id.
* @property {string} navigationProperty - A String representing the name of a single-valued navigation property. Useful when needed to retrieve information about a related record in a single request.
* @property {string} navigationPropertyKey - v.1.4.3+ A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata).
* @property {string} metadataAttributeType - v.1.4.3+ Casts the AttributeMetadata to a specific type. (Used in requests to Attribute Metadata).
* @property {boolean} noCache - If set to 'true', DynamicsWebApi adds a request header 'Cache-Control: no-cache'. Default value is 'false'.
* @property {string} savedQuery - A String representing the GUID value of the saved query.
* @property {string} userQuery - A String representing the GUID value of the user query.
* @property {boolean} mergeLabels - If set to 'true', DynamicsWebApi adds a request header 'MSCRM.MergeLabels: true'. Default value is 'false'.
* @property {boolean} isBatch - If set to 'true', DynamicsWebApi treats a request as a part of a batch request. Call ExecuteBatch to execute all requests in a batch. Default value is 'false'.
* @property {string} contentId - BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set.
* @property {boolean} trackChanges - Preference header 'odata.track-changes' is used to request that a delta link be returned which can subsequently be used to retrieve entity changes.
* @property {string} deltaLink - Delta link can be used to retrieve entity changes. Important! Change Tracking must be enabled for the entity.
*/
/**
* Constructor.
* @constructor
* @param {DWAConfig} [config] - configuration object
* @example
*var dynamicsWebApi = new DynamicsWebApi();
* @example
*var dynamicsWebApi = new DynamicsWebApi({ webApiVersion: '9.0' });
* @example
*var dynamicsWebApi = new DynamicsWebApi({
* webApiUrl: 'https:/myorg.api.crm.dynamics.com/api/data/v9.0/',
* includeAnnotations: 'OData.Community.Display.V1.FormattedValue'
*});
*/
function DynamicsWebApi(config) {
var _internalConfig = {
webApiVersion: "8.0",
webApiUrl: null,
impersonate: null,
impersonateAAD: null,
onTokenRefresh: null,
includeAnnotations: null,
maxPageSize: null,
returnRepresentation: null,
proxy: null,
};
var _isBatch = false;
var _batchRequestId;
if (!config) {
config = _internalConfig;
}
/**
* Sets the configuration parameters for DynamicsWebApi helper.
*
* @param {DWAConfig} config - configuration object
* @example
dynamicsWebApi.setConfig({ webApiVersion: '9.0' });
*/
this.setConfig = function (config) {
var isVersionDiffer = (config.webApiVersion || _internalConfig.webApiVersion) !== _internalConfig.webApiVersion;
if (config.webApiVersion) {
ErrorHelper.stringParameterCheck(config.webApiVersion, "DynamicsWebApi.setConfig", "config.webApiVersion");
_internalConfig.webApiVersion = config.webApiVersion;
}
if (config.webApiUrl) {
ErrorHelper.stringParameterCheck(config.webApiUrl, "DynamicsWebApi.setConfig", "config.webApiUrl");
_internalConfig.webApiUrl = config.webApiUrl;
} else {
if (!_internalConfig.webApiUrl || isVersionDiffer) {
_internalConfig.webApiUrl = Utility.initWebApiUrl(_internalConfig.webApiVersion);
}
}
if (config.impersonate) {
_internalConfig.impersonate = ErrorHelper.guidParameterCheck(config.impersonate, "DynamicsWebApi.setConfig", "config.impersonate");
}
if (config.impersonateAAD) {
_internalConfig.impersonateAAD = ErrorHelper.guidParameterCheck(config.impersonateAAD, "DynamicsWebApi.setConfig", "config.impersonateAAD");
}
if (config.onTokenRefresh) {
ErrorHelper.callbackParameterCheck(config.onTokenRefresh, "DynamicsWebApi.setConfig", "config.onTokenRefresh");
_internalConfig.onTokenRefresh = config.onTokenRefresh;
}
if (config.includeAnnotations) {
ErrorHelper.stringParameterCheck(config.includeAnnotations, "DynamicsWebApi.setConfig", "config.includeAnnotations");
_internalConfig.includeAnnotations = config.includeAnnotations;
}
if (config.timeout) {
ErrorHelper.numberParameterCheck(config.timeout, "DynamicsWebApi.setConfig", "config.timeout");
_internalConfig.timeout = config.timeout;
}
if (config.maxPageSize) {
ErrorHelper.numberParameterCheck(config.maxPageSize, "DynamicsWebApi.setConfig", "config.maxPageSize");
_internalConfig.maxPageSize = config.maxPageSize;
}
if (config.returnRepresentation) {
ErrorHelper.boolParameterCheck(config.returnRepresentation, "DynamicsWebApi.setConfig", "config.returnRepresentation");
_internalConfig.returnRepresentation = config.returnRepresentation;
}
if (config.useEntityNames) {
ErrorHelper.boolParameterCheck(config.useEntityNames, "DynamicsWebApi.setConfig", "config.useEntityNames");
_internalConfig.useEntityNames = config.useEntityNames;
}
/* webpack-strip-block:removed */
};
this.setConfig(config);
var _makeRequest = function (method, request, functionName, responseParams) {
request.isBatch = _isBatch;
request.requestId = _batchRequestId;
return new Promise(function (resolve, reject) {
Request.makeRequest(method, request, functionName, _internalConfig, responseParams, resolve, reject);
});
};
/**
* Sends an asynchronous request to create a new record.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
* @example
*var lead = {
* subject: "Test WebAPI",
* firstname: "Test",
* lastname: "WebAPI",
* jobtitle: "Title"
*};
*
*var request = {
* entity: lead,
* collection: "leads",
* returnRepresentation: true
*}
*
*dynamicsWebApi.createRequest(request).then(function (response) {
*}).catch(function (error) {
*});
*/
this.createRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.create", "request");
return _makeRequest("POST", request, "create").then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to create a new record.
*
* @param {Object} object - A JavaScript object valid for create operations.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string|Array} [prefer] - Sets a Prefer header value. For example: ['retrun=representation', 'odata.include-annotations="*"']
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @returns {Promise} D365 Web Api result
* @example
*var lead = {
* subject: "Test WebAPI",
* firstname: "Test",
* lastname: "WebAPI",
* jobtitle: "Title"
*};
*
*dynamicsWebApi.create(lead, "leads").then(function (id) {
*}).catch(function (error) {
*});
*/
this.create = function (object, collection, prefer, select) {
ErrorHelper.parameterCheck(object, "DynamicsWebApi.create", "object");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.create", "collection");
if (prefer) {
ErrorHelper.stringOrArrayParameterCheck(prefer, "DynamicsWebApi.create", "prefer");
}
if (select) {
ErrorHelper.arrayParameterCheck(select, "DynamicsWebApi.create", "select");
}
var request = {
collection: collection,
select: select,
prefer: prefer,
entity: object,
};
return this.createRequest(request);
};
/**
* Sends an asynchronous request to retrieve a record.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
* @example
*var request = {
* key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',
* collection: "leads",
* select: ["fullname", "subject"],
* ifnonematch: 'W/"468026"',
* includeAnnotations: "OData.Community.Display.V1.FormattedValue"
*};
*
*dynamicsWebApi.retrieveRequest(request).then(function (response) {
*
*}).catch(function (error) {
*
*});
*/
this.retrieveRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.retrieve", "request");
//copy locally
var isRef = request.select != null && request.select.length === 1 && request.select[0].endsWith("/$ref");
return _makeRequest("GET", request, "retrieve", { isRef: isRef }).then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to retrieve a record.
*
* @param {string} key - A String representing the GUID value or Aternate Key for the record to retrieve.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @param {string|Array} [expand] - A String or Array of Expand Objects representing the $expand Query Option value to control which related records need to be returned.
* @returns {Promise} D365 Web Api result
*/
this.retrieve = function (key, collection, select, expand) {
ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.retrieve", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.retrieve", "key");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.retrieve", "collection");
if (select && select.length) {
ErrorHelper.arrayParameterCheck(select, "DynamicsWebApi.retrieve", "select");
}
if (expand && expand.length) {
ErrorHelper.stringOrArrayParameterCheck(expand, "DynamicsWebApi.retrieve", "expand");
}
var request = {
collection: collection,
key: key,
select: select,
expand: expand,
};
return this.retrieveRequest(request);
};
/**
* Sends an asynchronous request to update a record.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
*/
this.updateRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.update", "request");
if (request.ifmatch == null) {
request.ifmatch = "*"; //to prevent upsert
}
//Metadata definitions, cannot be updated using "PATCH" method
var method = /EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions/.test(request.collection) ? "PUT" : "PATCH";
//copy locally
var ifmatch = request.ifmatch;
return _makeRequest(method, request, "update", { valueIfEmpty: true })
.then(function (response) {
return response.data;
})
.catch(function (error) {
if (ifmatch && error.status === 412) {
//precondition failed - not updated
return false;
}
//rethrow error otherwise
throw error;
});
};
/**
* Sends an asynchronous request to update a record.
*
* @param {string} key - A String representing the GUID value or Alternate Key for the record to update.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.
* @param {string} [prefer] - If set to "return=representation" the function will return an updated object
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @returns {Promise} D365 Web Api result
*/
this.update = function (key, collection, object, prefer, select) {
ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.update", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.update", "key");
ErrorHelper.parameterCheck(object, "DynamicsWebApi.update", "object");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.update", "collection");
if (prefer) {
ErrorHelper.stringOrArrayParameterCheck(prefer, "DynamicsWebApi.update", "prefer");
}
if (select) {
ErrorHelper.arrayParameterCheck(select, "DynamicsWebApi.update", "select");
}
var request = {
collection: collection,
key: key,
select: select,
prefer: prefer,
entity: object,
};
return this.updateRequest(request);
};
/**
* Sends an asynchronous request to update a single value in the record.
*
* @param {string} key - A String representing the GUID value or Alternate Key for the record to update.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} keyValuePair - keyValuePair object with a logical name of the field as a key and a value to update with. Example: {subject: "Update Record"}
* @param {string|Array} [prefer] - If set to "return=representation" the function will return an updated object
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @returns {Promise} D365 Web Api result
*/
this.updateSingleProperty = function (key, collection, keyValuePair, prefer, select) {
ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.updateSingleProperty", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.updateSingleProperty", "key");
ErrorHelper.parameterCheck(keyValuePair, "DynamicsWebApi.updateSingleProperty", "keyValuePair");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.updateSingleProperty", "collection");
var field = Object.keys(keyValuePair)[0];
var fieldValue = keyValuePair[field];
if (prefer) {
ErrorHelper.stringOrArrayParameterCheck(prefer, "DynamicsWebApi.updateSingleProperty", "prefer");
}
if (select) {
ErrorHelper.arrayParameterCheck(select, "DynamicsWebApi.updateSingleProperty", "select");
}
var request = {
collection: collection,
key: key,
select: select,
prefer: prefer,
navigationProperty: field,
data: { value: fieldValue },
};
return _makeRequest("PUT", request, "updateSingleProperty").then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to delete a record.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
*/
this.deleteRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.delete", "request");
//copy locally
var ifmatch = request.ifmatch;
return _makeRequest("DELETE", request, "delete", { valueIfEmpty: true })
.then(function (response) {
return response.data;
})
.catch(function (error) {
if (ifmatch && error.status === 412) {
//precondition failed - not deleted
return false;
} else {
//rethrow error otherwise
throw error;
}
});
};
/**
* Sends an asynchronous request to delete a record.
*
* @param {string} key - A String representing the GUID value or Alternate Key for the record to delete.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [propertyName] - The name of the property which needs to be emptied. Instead of removing a whole record only the specified property will be cleared.
* @returns {Promise} D365 Web Api result
*/
this.deleteRecord = function (key, collection, propertyName) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.deleteRecord", "collection");
if (propertyName != null) ErrorHelper.stringParameterCheck(propertyName, "DynamicsWebApi.deleteRecord", "propertyName");
var request = {
navigationProperty: propertyName,
collection: collection,
key: key,
};
return _makeRequest("DELETE", request, "deleteRecord").then(function () {
return;
});
};
/**
* Sends an asynchronous request to upsert a record.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
*/
this.upsertRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.upsert", "request");
//copy locally
var ifnonematch = request.ifnonematch;
var ifmatch = request.ifmatch;
return _makeRequest("PATCH", request, "upsert")
.then(function (response) {
return response.data;
})
.catch(function (error) {
if (ifnonematch && error.status === 412) {
//if prevent update
return;
} else if (ifmatch && error.status === 404) {
//if prevent create
return;
}
//rethrow error otherwise
throw error;
});
};
/**
* Sends an asynchronous request to upsert a record.
*
* @param {string} key - A String representing the GUID value or Alternate Key for the record to upsert.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.
* @param {string|Array} [prefer] - If set to "return=representation" the function will return an updated object
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @returns {Promise} D365 Web Api result
*/
this.upsert = function (key, collection, object, prefer, select) {
ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.upsert", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.upsert", "key");
ErrorHelper.parameterCheck(object, "DynamicsWebApi.upsert", "object");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.upsert", "collection");
if (prefer) {
ErrorHelper.stringOrArrayParameterCheck(prefer, "DynamicsWebApi.upsert", "prefer");
}
if (select) {
ErrorHelper.arrayParameterCheck(select, "DynamicsWebApi.upsert", "select");
}
var request = {
collection: collection,
key: key,
select: select,
prefer: prefer,
entity: object,
};
return this.upsertRequest(request);
};
var _uploadFileChunk = function (request, fileBytes, chunkSize, offset) {
offset = offset || 0;
Utility.setFileChunk(request, fileBytes, chunkSize, offset);
return _makeRequest("PATCH", request, "uploadFile").then(function (response) {
offset += chunkSize;
if (offset <= fileBytes.length) {
return _uploadFileChunk(request, fileBytes, chunkSize, offset);
}
return;
});
};
/**
* Upload file to a File Attribute
*
* @param {any} request - An object that represents all possible options for a current request.
*/
this.uploadFile = function (request) {
ErrorHelper.batchIncompatible("DynamicsWebApi.uploadFile", _isBatch);
ErrorHelper.parameterCheck(request, "DynamicsWebApi.uploadFile", "request");
var data = request.data;
delete request.data;
var internalRequest = Utility.copyObject(request);
internalRequest.transferMode = "chunked";
request.data = data;
return _makeRequest("PATCH", internalRequest, "uploadFile").then(function (response) {
internalRequest.url = response.data.location;
delete internalRequest.transferMode;
delete internalRequest.fieldName;
return _uploadFileChunk(internalRequest, request.data, response.data.chunkSize);
});
};
var _downloadFileChunk = function (request, bytesDownloaded, fileSize, data) {
bytesDownloaded = bytesDownloaded || 0;
fileSize = fileSize || 0;
data = data || "";
request.range = "bytes=" + bytesDownloaded + "-" + (bytesDownloaded + Utility.downloadChunkSize - 1);
request.downloadSize = "full";
return _makeRequest("GET", request, "downloadFile", { parse: true }).then(function (response) {
request.url = response.data.location;
data += response.data.value;
bytesDownloaded += Utility.downloadChunkSize;
if (bytesDownloaded <= response.data.fileSize) {
return _downloadFileChunk(request, bytesDownloaded, response.data.fileSize, data);
}
return {
fileName: response.data.fileName,
fileSize: response.data.fileSize,
data: Utility.convertToFileBuffer(data),
};
});
};
/**
* Download a file from a File Attribute
* @param {any} request - An object that represents all possible options for a current request.
*/
this.downloadFile = function (request) {
ErrorHelper.batchIncompatible("DynamicsWebApi.downloadFile", _isBatch);
ErrorHelper.parameterCheck(request, "DynamicsWebApi.downloadFile", "request");
var internalRequest = Utility.copyObject(request);
return _downloadFileChunk(internalRequest);
};
var retrieveMultipleRequest = function (request, nextPageLink) {
if (nextPageLink) {
ErrorHelper.stringParameterCheck(nextPageLink, "DynamicsWebApi.retrieveMultiple", "nextPageLink");
request.url = nextPageLink;
}
return _makeRequest("GET", request, "retrieveMultiple").then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to retrieve records.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {string} [nextPageLink] - Use the value of the @odata.nextLink property with a new GET request to return the next page of data. Pass null to retrieveMultipleOptions.
* @returns {Promise} D365 Web Api result
*/
this.retrieveMultipleRequest = retrieveMultipleRequest;
var _retrieveAllRequest = function (request, nextPageLink, records) {
records = records || [];
return retrieveMultipleRequest(request, nextPageLink).then(function (response) {
records = records.concat(response.value);
var pageLink = response.oDataNextLink;
if (pageLink) {
return _retrieveAllRequest(request, pageLink, records);
}
var result = { value: records };
if (response.oDataDeltaLink) {
result["@odata.deltaLink"] = response.oDataDeltaLink;
result.oDataDeltaLink = response.oDataDeltaLink;
}
return result;
});
};
/**
* Sends an asynchronous request to retrieve all records.
*
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise} D365 Web Api result
*/
this.retrieveAllRequest = function (request) {
ErrorHelper.batchIncompatible("DynamicsWebApi.retrieveAllRequest", _isBatch);
return _retrieveAllRequest(request);
};
/**
* Sends an asynchronous request to count records. IMPORTANT! The count value does not represent the total number of entities in the system. It is limited by the maximum number of entities that can be returned. Returns: Number
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.
* @returns {Promise} D365 Web Api result
*/
this.count = function (collection, filter) {
var request = {
collection: collection,
};
if (filter == null || (filter != null && !filter.length)) {
request.navigationProperty = "$count";
} else {
request.filter = filter;
request.count = true;
}
//if filter has not been specified then simplify the request
return _makeRequest("GET", request, "count", { toCount: request.count }).then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to count records. Returns: Number
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.
* @returns {Promise} D365 Web Api result
*/
this.countAll = function (collection, filter, select) {
ErrorHelper.batchIncompatible("DynamicsWebApi.countAll", _isBatch);
return _retrieveAllRequest({
collection: collection,
filter: filter,
select: select,
}).then(function (response) {
return response ? (response.value ? response.value.length : 0) : 0;
});
};
/**
* Sends an asynchronous request to retrieve records.
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - Use the $select system query option to limit the properties returned.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.
* @param {string} [nextPageLink] - Use the value of the @odata.nextLink property with a new GET request to return the next page of data. Pass null to retrieveMultipleOptions.
* @returns {Promise} D365 Web Api result
*/
this.retrieveMultiple = function (collection, select, filter, nextPageLink) {
return this.retrieveMultipleRequest(
{
collection: collection,
select: select,
filter: filter,
},
nextPageLink
);
};
/**
* Sends an asynchronous request to retrieve all records.
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - Use the $select system query option to limit the properties returned.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.
* @returns {Promise} D365 Web Api result
*/
this.retrieveAll = function (collection, select, filter) {
ErrorHelper.batchIncompatible("DynamicsWebApi.retrieveAll", _isBatch);
return _retrieveAllRequest({
collection: collection,
select: select,
filter: filter,
});
};
var executeFetchXml = function (collection, fetchXml, includeAnnotations, pageNumber, pagingCookie, impersonateUserId) {
ErrorHelper.stringParameterCheck(fetchXml, "DynamicsWebApi.executeFetchXml", "fetchXml");
//only add paging if there is no top
if (!/^<fetch.+top=/.test(fetchXml)) {
var replacementString = null;
if (!/^<fetch.+page=/.test(fetchXml)) {
pageNumber = pageNumber || 1;
ErrorHelper.numberParameterCheck(pageNumber, "DynamicsWebApi.executeFetchXml", "pageNumber");
replacementString = '$1 page="' + pageNumber + '"';
}
if (pagingCookie != null) {
ErrorHelper.stringParameterCheck(pagingCookie, "DynamicsWebApi.executeFetchXml", "pagingCookie");
replacementString += ' paging-cookie="' + pagingCookie + '"';
}
//add page number and paging cookie to fetch xml
if (replacementString)
fetchXml = fetchXml.replace(/^(<fetch)/, replacementString);
}
var request = {
collection: collection,
includeAnnotations: includeAnnotations,
impersonate: impersonateUserId,
fetchXml: fetchXml,
};
return _makeRequest("GET", request, "executeFetchXml", { pageNumber: pageNumber }).then(function (response) {
return response.data;
});
};
/**
* Sends an asynchronous request to execute FetchXml to retrieve records. Returns: DWA.Types.FetchXmlResponse
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.
* @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie
* @param {number} [pageNumber] - Page number.
* @param {string} [pagingCookie] - Paging cookie. For retrieving the first page, pagingCookie should be null.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.fetch = executeFetchXml;
/**
* Sends an asynchronous request to execute FetchXml to retrieve records. Returns: DWA.Types.FetchXmlResponse
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.
* @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie
* @param {number} [pageNumber] - Page number.
* @param {string} [pagingCookie] - Paging cookie. For retrieving the first page, pagingCookie should be null.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.executeFetchXml = executeFetchXml;
var _executeFetchXmlAll = function (collection, fetchXml, includeAnnotations, pageNumber, pagingCookie, impersonateUserId, records) {
records = records || [];
return executeFetchXml(collection, fetchXml, includeAnnotations, pageNumber, pagingCookie, impersonateUserId, records).then(function (response) {
records = records.concat(response.value);
if (response.PagingInfo) {
return _executeFetchXmlAll(
collection,
fetchXml,
includeAnnotations,
response.PagingInfo.nextPage,
response.PagingInfo.cookie,
impersonateUserId,
records
);
}
return { value: records };
});
};
var innerExecuteFetchXmlAll = function (collection, fetchXml, includeAnnotations, impersonateUserId) {
ErrorHelper.batchIncompatible("DynamicsWebApi.executeFetchXmlAll", _isBatch);
return _executeFetchXmlAll(collection, fetchXml, includeAnnotations, null, null, impersonateUserId);
};
/**
* Sends an asynchronous request to execute FetchXml to retrieve all records.
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.
* @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.fetchAll = innerExecuteFetchXmlAll;
/**
* Sends an asynchronous request to execute FetchXml to retrieve all records.
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.
* @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.executeFetchXmlAll = innerExecuteFetchXmlAll;
/**
* Associate for a collection-valued navigation property. (1:N or N:N)
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedCollection - Related name of the Entity Collection or Entity Logical name.
* @param {string} relatedKey - Related entity record id.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.associate = function (collection, primaryKey, relationshipName, relatedCollection, relatedKey, impersonateUserId) {
ErrorHelper.stringParameterCheck(relatedCollection, "DynamicsWebApi.associate", "relatedcollection");
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.associate", "relationshipName");
primaryKey = ErrorHelper.keyParameterCheck(primaryKey, "DynamicsWebApi.associate", "primaryKey");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.associate", "relatedKey");
var request = {
_additionalUrl: relationshipName + "/$ref",
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
data: { "@odata.id": relatedCollection + "(" + relatedKey + ")" },
};
return _makeRequest("POST", request, "associate").then(function () {});
};
/**
* Disassociate for a collection-valued navigation property.
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedKey - Related entity record id.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.disassociate = function (collection, primaryKey, relationshipName, relatedKey, impersonateUserId) {
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.disassociate", "relationshipName");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.disassociate", "relatedId");
var request = {
_additionalUrl: relationshipName + "(" + relatedKey + ")/$ref",
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
};
return _makeRequest("DELETE", request, "disassociate").then(function () {});
};
/**
* Associate for a single-valued navigation property. (1:N)
*
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} key - Entity record Id that contains an attribute.
* @param {string} singleValuedNavigationPropertyName - Single-valued navigation property name (usually it's a Schema Name of the lookup attribute).
* @param {string} relatedCollection - Related collection name that the lookup (attribute) points to.
* @param {string} relatedKey - Related entity record id that needs to be associated.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise} D365 Web Api result
*/
this.associateSingleValued = function (collection, key, singleValuedNavigationPropertyName, relatedCollection, relatedKey, impersonateUserId) {