-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathWebApiClient.Core.js.html
1076 lines (863 loc) · 40.8 KB
/
WebApiClient.Core.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebApiClient.Core.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="module-WebApiClient.Batch.html">Batch</a><ul class='methods'><li data-type='method'><a href="module-WebApiClient.Batch.html#buildPayload">buildPayload</a></li></ul></li><li><a href="module-WebApiClient.BatchRequest.html">BatchRequest</a><ul class='methods'><li data-type='method'><a href="module-WebApiClient.BatchRequest.html#stringify">stringify</a></li></ul></li><li><a href="module-WebApiClient.BatchResponse.html">BatchResponse</a></li><li><a href="module-WebApiClient.ChangeSet.html">ChangeSet</a><ul class='methods'><li data-type='method'><a href="module-WebApiClient.ChangeSet.html#stringify">stringify</a></li></ul></li><li><a href="module-WebApiClient.Response.html">Response</a></li><li><a href="WebApiClient.Promise.html">Promise</a></li><li><a href="WebApiClient.Requests.Request.html">Request</a></li></ul><h3>Modules</h3><ul><li><a href="module-Requests.html">Requests</a><ul class='methods'><li data-type='method'><a href="module-Requests.html#.Requests.Request#with">Requests.Request#with</a></li></ul></li><li><a href="module-WebApiClient.html">WebApiClient</a><ul class='methods'><li data-type='method'><a href="module-WebApiClient.html#.AppendToDefaultHeaders">AppendToDefaultHeaders</a></li><li data-type='method'><a href="module-WebApiClient.html#.Associate">Associate</a></li><li data-type='method'><a href="module-WebApiClient.html#.Configure">Configure</a></li><li data-type='method'><a href="module-WebApiClient.html#.Create">Create</a></li><li data-type='method'><a href="module-WebApiClient.html#.Delete">Delete</a></li><li data-type='method'><a href="module-WebApiClient.html#.Disassociate">Disassociate</a></li><li data-type='method'><a href="module-WebApiClient.html#.Execute">Execute</a></li><li data-type='method'><a href="module-WebApiClient.html#.Expand">Expand</a></li><li data-type='method'><a href="module-WebApiClient.html#.GetApiUrl">GetApiUrl</a></li><li data-type='method'><a href="module-WebApiClient.html#.GetDefaultHeaders">GetDefaultHeaders</a></li><li data-type='method'><a href="module-WebApiClient.html#.GetSetName">GetSetName</a></li><li data-type='method'><a href="module-WebApiClient.html#.Retrieve">Retrieve</a></li><li data-type='method'><a href="module-WebApiClient.html#.SendBatch">SendBatch</a></li><li data-type='method'><a href="module-WebApiClient.html#.SendRequest">SendRequest</a></li><li data-type='method'><a href="module-WebApiClient.html#.Update">Update</a></li></ul></li></ul>
</nav>
<div id="main">
<h1 class="page-title">WebApiClient.Core.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/* @preserve
* MIT License
*
* Copyright (c) 2016 Florian Krönert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/**
* This is the core functionality of Xrm-WebApi-Client
* No instantiation needed, it's a singleton.
* @module WebApiClient
*/
(function (undefined) {
"use strict";
var WebApiClient = {};
var batchName = "batch_UrlLimitExeedingRequest";
/**
* @description The API version that will be used when sending requests. Default is "8.0"
* @param {String}
* @memberof module:WebApiClient
*/
WebApiClient.ApiVersion = "8.0";
/**
* @description Informs about which version of WebApiClient you're using
* @param {string}
* @memberof module:WebApiClient
*/
WebApiClient.Version = "v0.0.0";
/**
* @description Checks for more pages when retrieving results. If set to true, all pages will be retrieved, if set to false, only the first page will be retrieved.
* @param {boolean}
* @memberof module:WebApiClient
*/
WebApiClient.ReturnAllPages = false;
/**
* @description Set to true for retrieving formatted error in style 'xhr.statusText: xhr.error.Message'. If set to false, error json will be returned.
* @param {boolean}
* @memberof module:WebApiClient
*/
WebApiClient.PrettifyErrors = true;
/**
* @description Set to false for sending all requests synchronously. True by default.
* @param {boolean}
* @memberof module:WebApiClient
*/
WebApiClient.Async = true;
/**
* @description Connection to use when being used in a single page app.
* @param {String}
* @memberof module:WebApiClient
*/
WebApiClient.ClientUrl = null;
/**
* @description Token to use for authenticating when being used in a single page app.
* @param {String}
* @memberof module:WebApiClient
*/
WebApiClient.Token = null;
// This is for ensuring that we use bluebird internally, so that calls to WebApiClient have no differing set of
// functions that can be applied to the Promise. For example Promise.finally would not be available without Bluebird.
var Promise = require("bluebird").noConflict();
function GetCrmContext() {
if (typeof (GetGlobalContext) !== "undefined") {
return GetGlobalContext();
}
if (typeof (Xrm) !== "undefined"){
return Xrm.Page.context;
}
}
function GetClientUrl () {
var context = GetCrmContext();
if(context)
{
return context.getClientUrl();
}
if (WebApiClient.ClientUrl) {
return WebApiClient.ClientUrl;
}
throw new Error("Failed to retrieve client url, is ClientGlobalContext.aspx available?");
}
function MergeResults (firstResponse, secondResponse) {
if (!firstResponse && !secondResponse) {
return null;
}
if (firstResponse && !secondResponse) {
return firstResponse;
}
if (!firstResponse && secondResponse) {
return secondResponse;
}
firstResponse.value = firstResponse.value.concat(secondResponse.value);
delete firstResponse["@odata.nextLink"];
delete firstResponse["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"];
return firstResponse;
}
function RemoveIdBrackets (id) {
if (!id) {
return id;
}
return id.replace("{", "").replace("}", "");
}
/**
* @description Builds the set name of a given entity name.
* @method GetSetName
* @param {String} entityName Logical name of the entity, such as "account"
* @param {String}[overriddenSetName] Override set name if it can't be infered from plural rules
* @memberof module:WebApiClient
* @return {String}
*/
WebApiClient.GetSetName = function (entityName, overriddenSetName) {
if (overriddenSetName) {
return overriddenSetName;
}
var ending = entityName.slice(-1);
switch(ending)
{
case 's':
return entityName + "es";
case 'y':
return entityName.substring(0, entityName.length - 1) + "ies";
default:
return entityName + "s";
}
};
var DefaultHeaders = [
{ key: "Accept", value: "application/json" },
{ key: "OData-Version", value: "4.0" },
{ key: "OData-MaxVersion", value: "4.0" },
{ key: "Content-Type", value: "application/json; charset=utf-8" }
];
/**
* @description Returns array of default headers.
* @method GetDefaultHeaders
* @return {Array<{key: String, value:String}>}
* @memberof module:WebApiClient
*/
WebApiClient.GetDefaultHeaders = function() {
return DefaultHeaders;
};
function VerifyHeader(header) {
if (!header.key || typeof(header.value) === "undefined") {
throw new Error("Each request header needs a key and a value!");
}
if(typeof(header.key) !== "string") {
throw new Error("Header key " + header.key + " is not a string");
}
if(typeof(header.value) !== "string") {
throw new Error("Header value " + header.value + " for key " + header.key + " is not a string");
}
}
/**
* @description Function for building the set name of a given entity name.
* @method AppendToDefaultHeaders
* @param {...{key:String, value:String}} var_args Headers as variable arguments
* @memberof module:WebApiClient
* @return {void}
*/
WebApiClient.AppendToDefaultHeaders = function () {
if (!arguments.length) {
return;
}
for(var i = 0; i < arguments.length; i++) {
var argument = arguments[i];
VerifyHeader(argument);
DefaultHeaders.push(argument);
}
};
function AppendHeaders(xhr, headers) {
if (headers) {
for (var i = 0; i < headers.length; i++) {
var header = headers[i];
VerifyHeader(header);
xhr.setRequestHeader(header.key, header.value);
}
}
}
function GetRecordUrl (parameters) {
var params = parameters || {};
if ((!params.entityName && !params.overriddenSetName) || (!params.entityId && !params.alternateKey)) {
throw new Error("Need entity name or overridden set name and entity id or alternate key for getting record url!");
}
var url = WebApiClient.GetApiUrl() + WebApiClient.GetSetName(params.entityName, params.overriddenSetName);
if (params.alternateKey) {
url += BuildAlternateKeyUrl(params);
} else {
url += "(" + RemoveIdBrackets(params.entityId) + ")";
}
return url;
}
function FormatError (xhr) {
if (xhr && xhr.response) {
var response = ParseResponse(xhr);
if (response instanceof WebApiClient.BatchResponse) {
var errors = "";
if (response.errors.length > 0) {
errors = response.errors.map(function(e) {
return e.code + ": " + e.message;
}).join("\n\r");
}
return xhr.status + " - " + errors;
}
var json = JSON.parse(xhr.response);
if (!WebApiClient.PrettifyErrors) {
json.xhrStatusText = xhr.statusText;
return JSON.stringify(json);
} else {
var error = "";
if (json.error) {
error = json.error.message;
}
return xhr.statusText + ": " + error;
}
}
return "";
}
function GetNextLink (response) {
return response["@odata.nextLink"];
}
function GetPagingCookie(response) {
return response["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"];
}
function SetCookie (pagingCookie, parameters) {
// Parse cookie that we retrieved with response
var parser = new DOMParser();
var cookieXml = parser.parseFromString(pagingCookie, "text/xml");
var cookie = cookieXml.documentElement;
var cookieAttribute = cookie.getAttribute("pagingcookie");
// In CRM 8.X orgs, fetch cookies where escaped twice. Since 9.X, they are only escaped once.
// Below indexOf check checks for the double escaped cookie string '<cookie page'.
// In CRM 9.X this will lead to no matches, as cookies start as '%3ccookie%20page'.
if (cookieAttribute && cookieAttribute.indexOf("%253ccookie%2520page") === 0) {
cookieAttribute = unescape(cookieAttribute);
}
var cookieValue = unescape(cookieAttribute);
var pageNumber = parseInt(/<cookie page="([\d]+)">/.exec(cookieValue)[1]) + 1;
// Parse our original fetch XML, we will inject the paging information in here
var fetchXml = parser.parseFromString(parameters.fetchXml, "text/xml");
var fetch = fetchXml.documentElement;
fetch.setAttribute("page", pageNumber);
fetch.setAttribute("paging-cookie", cookieValue);
// Serialize modified fetch with paging information
var serializer = new XMLSerializer();
return serializer.serializeToString(fetchXml);
}
function SetPreviousResponse (parameters, response) {
// Set previous response
parameters._previousResponse = response;
}
function MergeHeaders() {
var headers = [];
if (!arguments) {
return headers;
}
for(var i = 0; i < arguments.length; i++) {
var headersToAdd = arguments[i];
if (!headersToAdd || !Array.isArray(headersToAdd)) {
continue;
}
for (var j = 0; j < headersToAdd.length; j++) {
var header = headersToAdd[j];
VerifyHeader(header);
var addHeader = true;
for (var k = 0; k < headers.length; k++) {
if (headers[k].key === header.key) {
addHeader = false;
break;
}
}
if (addHeader) {
headers.push(header);
}
}
}
return headers;
}
function IsBatch(responseText) {
return responseText && /^--batchresponse_[a-fA-F0-9\-]+$/m.test(responseText);
}
function ParseResponse(xhr) {
var responseText = xhr.responseText;
// Check if it is a batch response
if (IsBatch(responseText)) {
return new WebApiClient.BatchResponse({
xhr: xhr
});
}
else {
return JSON.parse(xhr.responseText);
}
}
function IsOverlengthGet (method, url) {
return method && method.toLowerCase() === "get" && url && url.length > 2048;
}
function SendAsync(method, url, payload, parameters) {
var xhr = new XMLHttpRequest();
var promise = new Promise(function(resolve, reject) {
xhr.onload = function() {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 200){
var response = ParseResponse(xhr);
if (response instanceof WebApiClient.BatchResponse) {
// If it was an overlength fetchXml, that was sent as batch automatically, we don't want it to behave as a batch
if (parameters.isOverLengthGet) {
response = response.batchResponses[0].payload;
}
// If we received multiple responses, but not from overlength get, it was a custom batch. Just resolve all matches
else {
resolve(response);
}
}
var nextLink = GetNextLink(response);
var pagingCookie = GetPagingCookie(response);
// Since 9.X paging cookie is always added to response, even in queryParams retrieves
// In 9.X the morerecords flag can signal whether there are more records to be found
// In 8.X the flag was not present and instead the pagingCookie was only set if more records were available
var moreRecords = "@Microsoft.Dynamics.CRM.morerecords" in response ? response["@Microsoft.Dynamics.CRM.morerecords"] : true;
response = MergeResults(parameters._previousResponse, response);
// Results are paged, we don't have all results at this point
if (moreRecords && nextLink && (WebApiClient.ReturnAllPages || parameters.returnAllPages)) {
SetPreviousResponse(parameters, response);
resolve(SendAsync("GET", nextLink, null, parameters));
}
else if (parameters.fetchXml && moreRecords && pagingCookie && (WebApiClient.ReturnAllPages || parameters.returnAllPages)) {
var nextPageFetch = SetCookie(pagingCookie, parameters);
SetPreviousResponse(parameters, response);
parameters.fetchXml = nextPageFetch;
resolve(WebApiClient.Retrieve(parameters));
}
else {
resolve(response);
}
}
else if (xhr.status === 201) {
resolve(ParseResponse(xhr));
}
else if (xhr.status === 204) {
if (method.toLowerCase() === "post") {
resolve(xhr.getResponseHeader("OData-EntityId"));
}
// No content returned for delete, update, ...
else {
resolve(xhr.statusText);
}
}
else {
reject(new Error(FormatError(xhr)));
}
};
xhr.onerror = function() {
reject(new Error(FormatError(xhr)));
};
});
var headers = [];
if (IsOverlengthGet(method, url)) {
var batch = new WebApiClient.Batch({
requests: [new WebApiClient.BatchRequest({
method: method,
url: url,
payload: payload,
headers: parameters.headers
})],
async: true,
isOverLengthGet: true
});
return WebApiClient.SendBatch(batch);
}
xhr.open(method, url, true);
headers = MergeHeaders(headers, parameters.headers, DefaultHeaders);
AppendHeaders(xhr, headers);
// Bugfix for IE. If payload is undefined, IE would send "undefined" as request body
if (payload) {
// For batch requests, we just want to send a string body
if (typeof(payload) === "string") {
xhr.send(payload);
}
else {
xhr.send(JSON.stringify(payload));
}
} else {
xhr.send();
}
return promise;
}
function SendSync(method, url, payload, parameters) {
var xhr = new XMLHttpRequest();
var response;
var headers = [];
if (IsOverlengthGet(method, url)) {
var batch = new WebApiClient.Batch({
requests: [new WebApiClient.BatchRequest({
method: method,
url: url,
payload: payload,
headers: parameters.headers
})],
async: false,
isOverLengthGet: true
});
return WebApiClient.SendBatch(batch);
}
xhr.open(method, url, false);
headers = MergeHeaders(headers, parameters.headers, DefaultHeaders);
AppendHeaders(xhr, headers);
// Bugfix for IE. If payload is undefined, IE would send "undefined" as request body
if (payload) {
// For batch requests, we just want to send a string body
if (typeof(payload) === "string") {
xhr.send(payload);
}
else {
xhr.send(JSON.stringify(payload));
}
} else {
xhr.send();
}
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 200){
response = ParseResponse(xhr);
// If we received multiple responses, it was a custom batch. Just resolve all matches
if (response instanceof WebApiClient.BatchResponse) {
// If it was an overlength fetchXml, that was sent as batch automatically, we don't want it to behave as a batch
if (parameters.isOverLengthGet) {
response = response.batchResponses[0].payload;
} else {
return response;
}
}
var nextLink = GetNextLink(response);
var pagingCookie = GetPagingCookie(response);
// Since 9.X paging cookie is always added to response, even in queryParams retrieves
// In 9.X the morerecords flag can signal whether there are more records to be found
// In 8.X the flag was not present and instead the pagingCookie was only set if more records were available
var moreRecords = "@Microsoft.Dynamics.CRM.morerecords" in response ? response["@Microsoft.Dynamics.CRM.morerecords"] : true;
response = MergeResults(parameters._previousResponse, response);
// Results are paged, we don't have all results at this point
if (moreRecords && nextLink && (WebApiClient.ReturnAllPages || parameters.returnAllPages)) {
SetPreviousResponse(parameters, response);
SendSync("GET", nextLink, null, parameters);
}
else if (parameters.fetchXml && moreRecords && pagingCookie && (WebApiClient.ReturnAllPages || parameters.returnAllPages)) {
var nextPageFetch = SetCookie(pagingCookie, parameters);
SetPreviousResponse(parameters, response);
parameters.fetchXml = nextPageFetch;
WebApiClient.Retrieve(parameters);
}
}
else if (xhr.status === 201) {
response = ParseResponse(xhr);
}
else if (xhr.status === 204) {
if (method.toLowerCase() === "post") {
response = xhr.getResponseHeader("OData-EntityId");
}
// No content returned for delete, update, ...
else {
response = xhr.statusText;
}
}
else {
throw new Error(FormatError(xhr));
}
return response;
}
function GetAsync (parameters) {
if (typeof(parameters.async) !== "undefined") {
return parameters.async;
}
return WebApiClient.Async;
}
function BuildAlternateKeyUrl (params) {
if (!params || !params.alternateKey) {
return "";
}
var url = "(";
for (var i = 0; i < params.alternateKey.length; i++) {
var key = params.alternateKey[i];
var value = key.value;
if (typeof(key.value) !== "number") {
value = "'" + key.value + "'";
}
url += key.property + "=" + value;
if (i + 1 === params.alternateKey.length) {
url += ")";
}
else {
url += ",";
}
}
return url;
}
/**
* @description Sends request using given parameters.
* @method SendRequest
* @param {String} method Method type of request to send, such as "GET"
* @param {String} url Target URL for request.
* @param {Object} [payload] Payload for request.
* @param {Object} [parameters] - Parameters for sending the request
* @param {Boolean} [parameters.async] - True for sending async, false for sync. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] - Headers for appending to request
* @memberof module:WebApiClient
* @return {Promise<Object>|Object}
*/
WebApiClient.SendRequest = function (method, url, payload, parameters) {
var params = parameters || {};
// Fallback for request headers array as fourth parameter
if (Array.isArray(params)) {
params = {
headers: params
};
}
if (WebApiClient.Token) {
params.headers = params.headers || [];
params.headers.push({key: "Authorization", value: "Bearer " + WebApiClient.Token});
}
if (params.asBatch) {
return new WebApiClient.BatchRequest({
method: method,
url: url,
payload: payload,
headers: params.headers
});
}
var asynchronous = GetAsync(params);
if (asynchronous) {
return SendAsync(method, url, payload, params);
} else {
return SendSync(method, url, payload, params);
}
};
/**
* @description Applies configuration to WebApiClient.
* @method Configure
* @param {Object} configuration Object with keys named after WebApiClient Members, such as "Token"s
* @memberof module:WebApiClient
* @return {void}
*/
WebApiClient.Configure = function (configuration) {
for (var property in configuration) {
if (!configuration.hasOwnProperty(property)) {
continue;
}
WebApiClient[property] = configuration[property];
}
};
/**
* @description Gets the current base API url that is used.
* @method GetApiUrl
* @memberof module:WebApiClient
* @return {String}
*/
WebApiClient.GetApiUrl = function() {
return GetClientUrl() + "/api/data/v" + WebApiClient.ApiVersion + "/";
};
/**
* @description Creates a given record in CRM.
* @method Create
* @param {Object} parameters Parameters for creating record
* @param {String} parameters.entityName Entity name of record that should be created
* @param {String} [parameters.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {Object} parameters.entity Object containing record data
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<String>|Promise<object>|String|Object} - Returns Promise<Object> if return=representation header is set, otherwise Promise<String>. Just Object or String if sent synchronously.
*/
WebApiClient.Create = function(parameters) {
var params = parameters || {};
if ((!params.entityName && !params.overriddenSetName) || !params.entity) {
throw new Error("Entity name and entity object have to be passed!");
}
var url = WebApiClient.GetApiUrl() + WebApiClient.GetSetName(params.entityName, params.overriddenSetName);
return WebApiClient.SendRequest("POST", url, params.entity, params);
};
/**
* @description Retrieves records from CRM
* @method Retrieve
* @param {Object} parameters Parameters for retrieving records
* @param {String} parameters.entityName Entity name of records that should be retrieved
* @param {String} [parameters.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} [parameters.queryParams] Query Parameters to append to URL, such as ?$select=*
* @param {String} [parameters.fetchXml] Fetch XML query
* @param {String} [parameters.entityId] ID of entity to retrieve, will return single record
* @param {Array<property:string,value:string>} [parameters.alternateKey] Alternate key array for retrieving single record
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<object>|Object} - Returns Promise<Object> if asyncj, just Object if sent synchronously.
*/
WebApiClient.Retrieve = function(parameters) {
var params = parameters || {};
if (!params.entityName && !params.overriddenSetName) {
throw new Error("Entity name has to be passed!");
}
var url = WebApiClient.GetApiUrl() + WebApiClient.GetSetName(params.entityName, params.overriddenSetName);
if (params.entityId) {
url += "(" + RemoveIdBrackets(params.entityId) + ")";
}
else if (params.fetchXml) {
url += "?fetchXml=" + escape(params.fetchXml);
}
else if (params.alternateKey) {
url += BuildAlternateKeyUrl(params);
}
if (params.queryParams) {
url += params.queryParams;
}
return WebApiClient.SendRequest("GET", url, null, params);
};
/**
* @description Updates a given record in CRM.
* @method Update
* @param {Object} parameters Parameters for updating record
* @param {String} parameters.entityName Entity name of records that should be updated
* @param {String} [parameters.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} [parameters.entityId] ID of entity to update
* @param {Array<property:string,value:string>} [parameters.alternateKey] Alternate key array for updating record
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<String>|Promise<object>|String|Object} - Returns Promise<Object> if return=representation header is set, otherwise Promise<String>. Just Object or String if sent synchronously.
*/
WebApiClient.Update = function(parameters) {
var params = parameters || {};
if (!params.entity) {
throw new Error("Update object has to be passed!");
}
var url = GetRecordUrl(params);
return WebApiClient.SendRequest("PATCH", url, params.entity, params);
};
/**
* @description Deletes a given record in CRM.
* @method Delete
* @param {Object} parameters Parameters for deleting record
* @param {String} parameters.entityName Entity name of records that should be deleted
* @param {String} [parameters.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} [parameters.entityId] ID of entity to delete
* @param {Array<property:string,value:string>} [parameters.alternateKey] Alternate key array for deleting record
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<String>|String} - Returns Promise<String> if async, just String if sent synchronously.
*/
WebApiClient.Delete = function(parameters) {
var params = parameters || {};
var url = GetRecordUrl(params);
if (params.queryParams) {
url += params.queryParams;
}
return WebApiClient.SendRequest("DELETE", url, null, params);
};
/**
* @description Associates given records in CRM.
* @method Associate
* @param {Object} parameters Parameters for associating records
* @param {String} parameters.relationShip Name of relation ship to use for associating
* @param {Object} parameters.source Source entity for disassociating
* @param {String} [parameters.source.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} parameters.source.entityId ID of entity
* @param {String} parameters.source.entityName Logical name of entity, such as "account"
* @param {Object} parameters.target Target entity for disassociating
* @param {String} [parameters.target.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} parameters.target.entityId ID of entity
* @param {String} parameters.target.entityName Logical name of entity, such as "account"
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<String>|String} - Returns Promise<String> if async, just String if sent synchronously.
*/
WebApiClient.Associate = function(parameters) {
var params = parameters || {};
if (!params.relationShip) {
throw new Error("Relationship has to be passed!");
}
if (!params.source || !params.target) {
throw new Error("Source and target have to be passed!");
}
var targetUrl = GetRecordUrl(params.target);
var relationShip = "/" + params.relationShip + "/$ref";
var url = targetUrl + relationShip;
var payload = { "@odata.id": GetRecordUrl(params.source) };
return WebApiClient.SendRequest("POST", url, payload, params);
};
/**
* @description Disassociates given records in CRM.
* @method Disassociate
* @param {Object} parameters Parameters for disassociating records
* @param {String} parameters.relationShip Name of relation ship to use for disassociating
* @param {Object} parameters.source Source entity for disassociating
* @param {String} [parameters.source.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} parameters.source.entityId ID of entity
* @param {String} parameters.source.entityName Logical name of entity, such as "account"
* @param {Object} parameters.target Target entity for disassociating
* @param {String} [parameters.target.overriddenSetName] Plural name of entity, if not according to plural rules
* @param {String} parameters.target.entityId ID of entity
* @param {String} parameters.target.entityName Logical name of entity, such as "account"
* @param {Boolean} [parameters.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [parameters.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<String>|String} - Returns Promise<String> if async, just String if sent synchronously.
*/
WebApiClient.Disassociate = function(parameters) {
var params = parameters || {};
if (!params.relationShip) {
throw new Error("Relationship has to be passed!");
}
if (!params.source || !params.target) {
throw new Error("Source and target have to be passed!");
}
if (!params.source.entityId) {
throw new Error("Source needs entityId set!");
}
var targetUrl = GetRecordUrl(params.target);
var relationShip = "/" + params.relationShip + "(" + RemoveIdBrackets(params.source.entityId) + ")/$ref";
var url = targetUrl + relationShip;
return WebApiClient.SendRequest("DELETE", url, null, params);
};
/**
* @description Executes the given request in CRM.
* @method Execute
* @param {Object} request Request to send, must be in prototype chain of WebApiClient.Requests.Request.
* @param {Boolean} [request.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [request.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<Object>|Object} - Returns Promise<Object> if async, just Object if sent synchronously.
*/
WebApiClient.Execute = function(request) {
if (!request) {
throw new Error("You need to pass a request!");
}
if (!(request instanceof WebApiClient.Requests.Request)) {
throw new Error("Request for execution must be in prototype chain of WebApiClient.Request");
}
return WebApiClient.SendRequest(request.method, request.buildUrl(), request.payload, request);
};
/**
* @description Sends the given batch to CRM.
* @method SendBatch
* @param {Object} batch Batch to send to CRM
* @param {Boolean} [batch.async] True for sending asynchronous, false for synchronous. Defaults to true.
* @param {Array<key:string,value:string>} [batch.headers] Headers to attach to request
* @memberof module:WebApiClient
* @return {Promise<Object>|Object} - Returns Promise<Object> if async, just Object if sent synchronously.
*/
WebApiClient.SendBatch = function(batch) {
if (!batch) {
throw new Error("You need to pass a batch!");
}
if (!(batch instanceof WebApiClient.Batch)) {
throw new Error("Batch for execution must be a WebApiClient.Batch object");
}
var url = WebApiClient.GetApiUrl() + "$batch";
batch.headers = batch.headers || [];
batch.headers.push({key: "Content-Type", value: "multipart/mixed;boundary=" + batch.name});
var payload = batch.buildPayload();
return WebApiClient.SendRequest("POST", url, payload, batch);
};
/**
* @description Expands all odata.nextLink (deferred) properties for an array of records.
* @method Expand
* @param {Object} parameters Configuration for expanding