aappddeevv

batch hack

Sep 30th, 2017
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CRMWebAPI.prototype.batch = function (entity, fetchXml, QueryOptions) {
  2.     const self = this
  3.  
  4.     // build the body
  5.     var body = '--batch_contactfetch\n'
  6.     body += 'Content-Type: application/http\n'
  7.     body += 'Content-Transfer-Encoding: binary\n'
  8.     body += '\n'
  9.     body += 'GET ' + self.config.APIUrl + `${entity}?fetchXml=${encodeURIComponent(fetchXml)} HTTP/1.1\n`
  10.     body += 'Content-Type: application/json\n'
  11.     body += 'OData-Version: 4.0\n'
  12.     body += 'OData-MaxVersion: 4.0\n'
  13.     body += '\n'
  14.     body += '--batch_contactfetch--'
  15.  
  16.     return new Promise(function (resolve, reject) {
  17.         const url = self._BuildQueryURL("$batch", QueryOptions, self.config)
  18.         self._log('ODataUrl',url)
  19.         //self._GetHttpRequest(self.config, "POST", url, { // won't work, additive headers
  20.         self._hack(self.config, "POST", url, {
  21.             'data': body,
  22.             headers: {
  23.                 "Content-Type": "multipart/mixed;boundary=batch_contactfetch"
  24.             }
  25.         }, function (err, res) { // callback
  26.             if (err != false) {
  27.                 self._log('Errors','batch error',res)
  28.                 reject(res)
  29.             } else {
  30.                 //if(DEBUG) console.log("raw r", res)
  31.                 var data = JSON.parse(self._sliceBatchResponse(res.response), self._DateReviver)
  32.                 if(data.error) {
  33.                     // its really an error
  34.                     self._log('Errors','batch error', res)
  35.                     reject(data.error)
  36.                     return
  37.                 }
  38.                 var nextLink = data['@odata.nextLink']
  39.                 var recordCount = data['@odata.count']
  40.                 var response = {
  41.                     List: data.value,
  42.                     Count: recordCount
  43.                 }
  44.                 if ((QueryOptions != null) && (QueryOptions.RecordAction != null))
  45.                 {
  46.                     response.List.forEach(function(record){
  47.                         QueryOptions.RecordAction(record)
  48.                     });
  49.                     response.List = [];
  50.                 }
  51.                 if ((QueryOptions != null) && (QueryOptions.PageAction != null))
  52.                 {                                              
  53.                     QueryOptions.PageAction(response.List)
  54.                 response.List = []             
  55.         }                      
  56.         if (!nextLink) {
  57.                     resolve(response)
  58.                 } else {
  59.                     if(DEBUG) console.log("NEXT LINK BUT NEED TO IMPLEMENT WHILST!!!")
  60.                     if(DEBUG) console.log("response", data)
  61.                     resolve(response)
  62.                     // the lib has page processing code here...copy and paste it!
  63.                 }
  64.             }
  65.         })
  66.     })
  67. }
  68.  
  69. CRMWebAPI.prototype._hack = function (config, method, url, payload, callback) {
  70.     var self = this;
  71.     var req = new XMLHttpRequest();
  72.     //req.open(method, encodeURI(url), true);
  73.     req.open(method, url, true);
  74.     if (config.AccessToken != null) req.setRequestHeader("Authorization", "Bearer " + config.AccessToken);
  75.     req.setRequestHeader("Accept", "application/json");
  76.     req.setRequestHeader("OData-MaxVersion", "4.0");
  77.     req.setRequestHeader("OData-Version", "4.0");
  78.     if (config.callerId) req.setRequestHeader("MSCRMCallerID", config.callerId);       
  79.     if (config.CallerID) req.setRequestHeader("MSCRMCallerID", config.CallerID);       
  80.     if (['POST', 'PUT', 'PATCH'].indexOf(method) >= 0) {
  81.     req.setRequestHeader("Content-Length", payload.data.length);
  82.     //req.setRequestHeader("Content-Type", "application/json");
  83.     }
  84.     if (payload.headers !== 'undefined') {
  85.     for (var name in payload.headers) {
  86.         req.setRequestHeader(name, payload.headers[name]);
  87.     }
  88.     }
  89.     req.onreadystatechange = function () {
  90.     if (this.readyState == 4 /* complete */ ) {
  91.         req.onreadystatechange = null;
  92.         if ((this.status >= 200) && (this.status < 300)) {
  93.         callback(false, {
  94.             'response': this.response,
  95.             'headers': self.parseResponseHeaders(this.getAllResponseHeaders())
  96.         });
  97.         } else {
  98.         callback(true, this)
  99.         }
  100.     }
  101.     };
  102.     if (['POST', 'PUT', 'PATCH'].indexOf(method) >= 0) {
  103.     req.send(payload.data);
  104.     } else {
  105.     req.send();
  106.     }
  107. }
  108.  
  109. CRMWebAPI.prototype._sliceBatchResponse = function(response) {
  110.     const start = response.indexOf("{")
  111.     const end = response.lastIndexOf("}")+1
  112.     //console.log("stats", start, end, response[start], response[end-1])
  113.     //console.log("parsing", response.substring(start, end))
  114.     return response.substring(start, end)
  115. }
Add Comment
Please, Sign In to add comment