-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch-salesforce.js
355 lines (327 loc) · 11.9 KB
/
fetch-salesforce.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
* @file Lightweight access to Salesforce REST API.
* @author Jason Verber <[email protected]>
*/
'use strict';
var salesforceSession = (_OAuthUrl = document.location.toString(), {
_instanceUrl,
_servicesPath = '/services/data/',
version = '43.0'
} = {}) => {
var _authenticated = false,
_expired = false,
_OAuthVars = {},
_requests = 0,
_requestErrors = 0,
_servicesPath = '/services/data/',
records,
searchRecords,
insertResults,
updateResults,
deleteResults,
soql,
sosl,
version;
const _url = (path='') => _OAuthVars.instance_url + _servicesPath + 'v' + version + '/' + path;
var _OAuthVarPairs = _OAuthUrl.split('#')[1].split('&');
for (let i = 0; i < _OAuthVarPairs.length; i++) {
let pair = _OAuthVarPairs[i].split('=');
_OAuthVars[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
if (_instanceUrl) _OAuthVars.instance_url = _instanceUrl;
/**
* Makes a Salesforce request.
* @private
* @param {string} method The HTTP method to use.
* @param {string} action The action represented by a query string to be appended to the Salesforce URL.
* @param {object} payload Optional payload for inclusion in this request.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {string} Response from fetch request.
*/
const _request = async (method, action, payload, optionalParameters, retry) => {
var cacheString = method+"-"+action;
var url = _url(action);
optionalParameters = _parameters(optionalParameters);
optionalParameters.method = method;
if (payload) {
var jPayload = JSON.stringify(payload);
optionalParameters.headers['Content-Type'] = "application/json";
optionalParameters.body = jPayload;
}
try {
_requests++;
var request = await fetch(url, optionalParameters);
var response = (method.toLowerCase() == "patch") ? request.getResponseCode() : await request.json();
return response;
} catch(e){
_requestErrors++;
if (!retry) retry = 0;
if (retry < 3) {
return _request(method, action, payload, optionalParameters, retry+1);
}
console.log("EXCEPTION!!!");
throw "Salesforce " + method.toUpperCase() + " request failed!";
return false;
}
};
/**
* Makes a Salesforce GET request.
* @private
* @param {string} action The action represented by a query string to be appended to the Salesforce URL.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {string} Response from fetch request.
*/
const _get = async (action, optionalParameters) => {
if (Array.isArray(action)) {
return this.batch(action, optionalParameters);
}
if (_url(action).length > 2048) { //A long query is going to fail because of Google Script limitations to URL length. Workaround by POST via batch.
var aBatch = [{method:"GET",url:'v' + version + '/' + action}];
return this.batch(aBatch, optionalParameters).results[0].result; //It's a batch of just one item, so we just need that first (and only) result.
}
return await _request("get", action, null, optionalParameters);
};
/**
* Makes a Salesforce POST request.
* @private
* @param {string} action The action represented by a query string to be appended to the Salesforce URL.
* @param {object} payload Optional payload for inclusion in this request.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {string} Response from fetch request.
*/
const _post = async (action, payload, optionalParameters) => {
return await _request("post", action, payload, optionalParameters);
};
/**
* Makes a Salesforce PATCH request.
* @private
* @param {string} action The action represented by a query string to be appended to the Salesforce URL.
* @param {object} payload Payload for inclusion in this request.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {string} Response from fetch request.
*/
const _patch = async (action, payload, optionalParameters) => {
return await _request("patch", action, payload, optionalParameters);
};
/**
* Gets HTTP headers and applies them to any other optional parameters.
* @private
* @param {object} optionalParameters Optional parameters for fetch requests.
* @returns {object} Parameters object for fetch requests.
*/
const _parameters = (optionalParameters) => {
var httpheaders = {Authorization: _OAuthVars.token_type + ' ' + _OAuthVars.access_token};
if (optionalParameters) {
optionalParameters.headers = httpheaders;
} else {
optionalParameters = {headers: httpheaders};
}
return optionalParameters;
};
return {
records,
searchRecords,
insertResults,
updateResults,
deleteResults,
soql,
sosl,
version,
/**
* Get a Salesforce object.
* @param {string} SObjectName The type of object to get.
* @param {string} id The id of the object to get.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {promise} Promise resolving to array with the record returned.
*/
async get (SObjectName, id, parameters){
let url = "sobjects/"+encodeURIComponent(SObjectName)+"/"+encodeURIComponent(id);
try{
parameters = _parameters(parameters);
let results = await _get(url, parameters);
this.records = [results];
return this.records;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.records = false;
throw "Get failed!";
return false;
}
},
/**
* Perform a Salesforce query.
* @param {string} mySoql The query to execute. If none provided, uses this.soql.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {promise} Promise resolving to array of records returned by query.
*/
async query (mySoql=this.soql, parameters){
this.soql = mySoql;
let query = "query?q="+encodeURIComponent(this.soql);
try{
parameters = _parameters(parameters);
let results = await _get(query, parameters);
this.records = results.records;
while (results.nextRecordsUrl != undefined) {
let results = await _get(results.nextRecordsUrl, _parameters());
this.records = this.records.concat(results.records);
}
return this.records;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.records = false;
throw "Query failed!";
return false;
}
},
/**
* Perform a Salesforce search.
* @param {string} mySosl The search to execute. If none provided, uses this.sosl.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {promise} Promise resolving to array of records returned by search.
*/
async search (mySosl=this.sosl, parameters){
this.sosl = mySosl;
let search = "search?q="+encodeURIComponent(this.sosl);
try{
parameters = _parameters(parameters);
let results = await _get(search, parameters);
this.searchRecords = results.searchRecords;
while (results.nextRecordsUrl != undefined) {
let results = await _get(results.nextRecordsUrl, _parameters());
this.searchRecords = this.searchRecords.concat(results.searchRecords);
}
return this.searchResults;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.searchRecords = false;
throw "Search failed!";
return false;
}
},
/**
* Makes a Salesforce BATCH request.
* @param {array} requests An array of the requests to be made.
* @param {object} optionalParameters Parameters for the fetch request.
* @returns {string} Response from fetch requests.
*/
async batch (requests, optionalParameters) {
var action = "composite/batch/";
if (!requests[0].method){
for (var i = 0; i < requests.length; i++){
requests[i] = {method:"GET",url:'v' + version + '/' + requests[i]};
}
}
var batchResponses = false;
while (requests.length > 0) {
var batchRequests = requests.splice(0,25);
var payload = {"batchRequests" : batchRequests};
try {
var thisResponse = await _post(action, payload, optionalParameters);
if (!batchResponses) batchResponses = thisResponse; else batchResponses.results.concat(thisResponse.results);
_requests--; //Don't count this request, it's part of a batch request that we've broken up for length reasons.
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
throw "Salesforce batch request failed!";
return false;
}
}
_requests++
return batchResponses;
},
/**
* Insert Salesforce records.
* @param {array} oRecords An array of the records to be inserted.
* @returns {array} An array of Salesforce records with Ids.
*/
async insert (oRecords){
//If we have only one record and it has attributes and a type then use it.
if (oRecords && oRecords.attributes && oRecords.attributes.type) oRecords = [oRecords];
//Any records to be submitted need to be in an array, and each object in the array needs .attributes and .type
if (!oRecords || !Array.isArray(oRecords) || !oRecords[0].attributes || !oRecords[0].attributes.type) throw new Error("No valid records to insert!");
var type = oRecords[0].attributes.type;
//Special URL for multiple oRecords.
var url = "composite/tree/"+type+"/";
//Initialize the array for our results.
this.insertReults = [];
try {
//Batches of 200 (maximum allowed by Salesforce)
while (oRecords.length > 0) {
var oRecordsBatch = oRecords.splice(0,200);
var payload = {"records" : oRecordsBatch};
this.insertReults = this.insertReults.concat(await _post(url, payload).results);
}
return this.insertReults;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.insertResults = false;
throw "Salesforce "+type+" insertion failed!";
return false;
}
},
/**
* Update Salesforce records.
* @param {array} oRecords An array of the records to be updated.
* @returns {array} An array of Salesforce records with Ids.
*/
async update (oRecords){
//If we have only one record and it has attributes and a type then use it.
if (oRecords && oRecords.attributes && oRecords.attributes.type) oRecords = [oRecords];
//Any records to be submitted need to be in an array, and each object in the array needs .attributes and .type
if (!oRecords || !Array.isArray(oRecords) || !oRecords[0].attributes || !oRecords[0].attributes.type) throw new Error("No valid records to update!");
var type = oRecords[0].attributes.type;
//Special URL for multiple oRecords.
var url = "composite/sobjects?_HttpMethod=PATCH";
//Initialize the array for our results.
this.updateResults = [];
try {
//Batches of 200 (maximum allowed by Salesforce)
while (oRecords.length > 0) {
var oRecordsBatch = oRecords.splice(0,200);
var payload = {"records" : oRecordsBatch};
this.updateResults = this.updateResults.concat(await _post(url, payload));
}
return this.updateResults;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.updateResults = false;
throw "Salesforce "+type+" update failed!";
return false;
}
},
/**
* Delete Salesforce records.
* @param {array} sIds An array of the IDs to be deleted.
* @returns {array} An array of Salesforce DeleteResult objects.
*/
async delete (sIds){
//If we have only one record and it has attributes and a type then use it.
if (sIds && !Array.isArray(sIds)) sIds = [sIds];
//Any records to be submitted need to be in an array, and each object in the array needs .attributes and .type
if (!sIds) throw new Error("No valid IDs to delete!");
//Special URL for multiple sIDs
var url = "composite/sobjects?_HttpMethod=DELETE&ids=";
//Initialize the array for our results.
this.deleteResults = [];
try {
//Batches of 200 (maximum allowed by Salesforce)
while (sIds.length > 0) {
var sIdsBatch = sIds.splice(0,200);
this.deleteResults = this.deleteResults.concat(await _post(url+sIdsBatch.join(",")));
}
return this.deleteResults;
} catch(e){
console.log("EXCEPTION!!!");
console.log(e);
this.updateResults = false;
throw "Salesforce delete failed!";
return false;
}
}
}
};