jsforce
Version:
Salesforce API Library for JavaScript
3 lines (2 loc) • 12.5 kB
JavaScript
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t=t.jsforce||(t.jsforce={}),t=t.modules||(t.modules={}),t=t.api||(t.api={}),t.Bulk=e()}}(function(){return function(){function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var h=n[s]={exports:{}};t[s][0].call(h.exports,function(e){var n=t[s][1][e];return o(n||e)},h,h.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}return e}()({1:[function(e,t,n){(function(e){"use strict";var n=window.jsforce.require("inherits"),r=window.jsforce.require("readable-stream"),o=r.Duplex,i=window.jsforce.require("events"),s=window.jsforce.require("lodash/core"),a=window.jsforce.require("multistream"),u=window.jsforce.require("./core"),c=window.jsforce.require("./record-stream"),h=window.jsforce.require("./promise"),l=window.jsforce.require("./http-api"),p=function(e,t,n,r,o){this._bulk=e,this.type=t,this.operation=n,this.options=r||{},this.id=o,this.state=this.id?"Open":"Unknown",this._batches={}};n(p,i.EventEmitter),p.prototype.info=function(e){return this._jobInfo||(this._jobInfo=this.check()),this._jobInfo.thenCall(e)},p.prototype.open=function(e){var t=this,n=this._bulk;n._logger;if(!this._jobInfo){var r=this.operation.toLowerCase();"harddelete"===r&&(r="hardDelete");var o=['<?xml version="1.0" encoding="UTF-8"?>','<jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">',"<operation>"+r+"</operation>","<object>"+this.type+"</object>",this.options.extIdField?"<externalIdFieldName>"+this.options.extIdField+"</externalIdFieldName>":"",this.options.concurrencyMode?"<concurrencyMode>"+this.options.concurrencyMode+"</concurrencyMode>":"",this.options.assignmentRuleId?"<assignmentRuleId>"+this.options.assignmentRuleId+"</assignmentRuleId>":"","<contentType>CSV</contentType>","</jobInfo>"].join("");this._jobInfo=n._request({method:"POST",path:"/job",body:o,headers:{"Content-Type":"application/xml; charset=utf-8"},responseType:"application/xml"}).then(function(e){return t.emit("open",e.jobInfo),t.id=e.jobInfo.id,t.state=e.jobInfo.state,e.jobInfo},function(e){throw t.emit("error",e),e})}return this._jobInfo.thenCall(e)},p.prototype.createBatch=function(){var e=new f(this),t=this;return e.on("queue",function(){t._batches[e.id]=e}),e},p.prototype.batch=function(e){var t=this._batches[e];return t||(t=new f(this,e),this._batches[e]=t),t},p.prototype.check=function(e){var t=this,n=this._bulk,r=n._logger;return this._jobInfo=this._waitAssign().then(function(){return n._request({method:"GET",path:"/job/"+t.id,responseType:"application/xml"})}).then(function(e){return r.debug(e.jobInfo),t.id=e.jobInfo.id,t.type=e.jobInfo.object,t.operation=e.jobInfo.operation,t.state=e.jobInfo.state,e.jobInfo}),this._jobInfo.thenCall(e)},p.prototype._waitAssign=function(e){return(this.id?h.resolve({id:this.id}):this.open()).thenCall(e)},p.prototype.list=function(e){var t=this,n=this._bulk,r=n._logger;return this._waitAssign().then(function(){return n._request({method:"GET",path:"/job/"+t.id+"/batch",responseType:"application/xml"})}).then(function(e){r.debug(e.batchInfoList.batchInfo);var t=e.batchInfoList;return t=s.isArray(t.batchInfo)?t.batchInfo:[t.batchInfo]}).thenCall(e)},p.prototype.close=function(){var e=this;return this._changeState("Closed").then(function(t){return e.id=null,e.emit("close",t),t},function(t){throw e.emit("error",t),t})},p.prototype.abort=function(){var e=this;return this._changeState("Aborted").then(function(t){return e.id=null,e.emit("abort",t),t},function(t){throw e.emit("error",t),t})},p.prototype._changeState=function(e,t){var n=this,r=this._bulk,o=r._logger;return this._jobInfo=this._waitAssign().then(function(){var t=['<?xml version="1.0" encoding="UTF-8"?>','<jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">',"<state>"+e+"</state>","</jobInfo>"].join("");return r._request({method:"POST",path:"/job/"+n.id,body:t,headers:{"Content-Type":"application/xml; charset=utf-8"},responseType:"application/xml"})}).then(function(e){return o.debug(e.jobInfo),n.state=e.jobInfo.state,e.jobInfo}),this._jobInfo.thenCall(t)};var f=function(e,t){f.super_.call(this,{objectMode:!0}),this.job=e,this.id=t,this._bulk=e._bulk,this._deferred=h.defer(),this._setupDataStreams()};n(f,r.Writable),f.prototype._setupDataStreams=function(){var e=this,t={nullValue:"#N/A"};this._uploadStream=new c.Serializable,this._uploadDataStream=this._uploadStream.stream("csv",t),this._downloadStream=new c.Parsable,this._downloadDataStream=this._downloadStream.stream("csv",t),this.on("finish",function(){e._uploadStream.end()}),this._uploadDataStream.once("readable",function(){e.job.open().then(function(){e._uploadDataStream.pipe(e._createRequestStream())})});var n=this._dataStream=new o;n._write=function(t,n,r){e._uploadDataStream.write(t,n,r)},n.on("finish",function(){e._uploadDataStream.end()}),this._downloadDataStream.on("readable",function(){n.read(0)}),this._downloadDataStream.on("end",function(){n.push(null)}),n._read=function(t){for(var r;null!==(r=e._downloadDataStream.read());)n.push(r)}},f.prototype._createRequestStream=function(){var e=this,t=e._bulk,n=t._logger;return t._request({method:"POST",path:"/job/"+e.job.id+"/batch",headers:{"Content-Type":"text/csv"},responseType:"application/xml"},function(t,r){t?e.emit("error",t):(n.debug(r.batchInfo),e.id=r.batchInfo.id,e.emit("queue",r.batchInfo))}).stream()},f.prototype._write=function(e,t,n){e=s.clone(e),"insert"===this.job.operation?delete e.Id:"delete"===this.job.operation&&(e={Id:e.Id}),delete e.type,delete e.attributes,this._uploadStream.write(e,t,n)},f.prototype.stream=function(){return this._dataStream},f.prototype.run=f.prototype.exec=f.prototype.execute=function(e,t){var n=this;if("function"==typeof e&&(t=e,e=null),this._result)throw new Error("Batch already executed.");var r=h.defer();if(this._result=r.promise,this._result.then(function(e){n._deferred.resolve(e)},function(e){n._deferred.reject(e)}),this.once("response",function(e){r.resolve(e)}),this.once("error",function(e){r.reject(e)}),s.isObject(e)&&s.isFunction(e.pipe))e.pipe(this._dataStream);else{var o;s.isArray(e)?(s.forEach(e,function(e){Object.keys(e).forEach(function(t){"boolean"==typeof e[t]&&(e[t]=String(e[t]))}),n.write(e)}),n.end()):s.isString(e)&&(o=e,this._dataStream.write(o,"utf8"),this._dataStream.end())}return this.thenCall(t)},f.prototype.then=function(e,t,n){return this._deferred.promise.then(e,t,n)},f.prototype.thenCall=function(t){return s.isFunction(t)&&this.then(function(n){e.nextTick(function(){t(null,n)})},function(n){e.nextTick(function(){t(n)})}),this},f.prototype.check=function(e){var t=this._bulk,n=t._logger,r=this.job.id,o=this.id;if(!r||!o)throw new Error("Batch not started.");return t._request({method:"GET",path:"/job/"+r+"/batch/"+o,responseType:"application/xml"}).then(function(e){return n.debug(e.batchInfo),e.batchInfo}).thenCall(e)},f.prototype.poll=function(e,t){var n=this,r=this.job.id,o=this.id;if(!r||!o)throw new Error("Batch not started.");var i=(new Date).getTime(),s=function(){var a=(new Date).getTime();if(i+t<a){var u=new Error("Polling time out. Job Id = "+r+" , batch Id = "+o);return u.name="PollingTimeout",u.jobId=r,u.batchId=o,void n.emit("error",u)}n.check(function(t,r){t?n.emit("error",t):"Failed"===r.state?parseInt(r.numberRecordsProcessed,10)>0?n.retrieve():n.emit("error",new Error(r.stateMessage)):"Completed"===r.state?n.retrieve():(n.emit("progress",r),setTimeout(s,e))})};setTimeout(s,e)},f.prototype.retrieve=function(e){var t=this,n=this._bulk,r=this.job.id,o=this.job,i=this.id;if(!r||!i)throw new Error("Batch not started.");return o.info().then(function(e){return n._request({method:"GET",path:"/job/"+r+"/batch/"+i+"/result"})}).then(function(e){var a;if("query"===o.operation){n._conn,e["result-list"].result;a=e["result-list"].result,a=s.map(s.isArray(a)?a:[a],function(e){return{id:e,batchId:i,jobId:r}})}else a=s.map(e,function(e){return{id:e.Id||null,success:"true"===e.Success,errors:e.Error?[e.Error]:[]}});return t.emit("response",a),a}).fail(function(e){throw t.emit("error",e),e}).thenCall(e)},f.prototype.result=function(e){var t=this.job.id,n=this.id;if(!t||!n)throw new Error("Batch not started.");var r=new c.Parsable,o=r.stream("csv");this._bulk._request({method:"GET",path:"/job/"+t+"/batch/"+n+"/result/"+e,responseType:"application/octet-stream"}).stream().pipe(o);return r};var d=function(){d.super_.apply(this,arguments)};n(d,l),d.prototype.beforeSend=function(e){e.headers=e.headers||{},e.headers["X-SFDC-SESSION"]=this._conn.accessToken},d.prototype.isSessionExpired=function(e){return 400===e.statusCode&&/<exceptionCode>InvalidSessionId<\/exceptionCode>/.test(e.body)},d.prototype.hasErrorInResponseBody=function(e){return!!e.error},d.prototype.parseError=function(e){return{errorCode:e.error.exceptionCode,message:e.error.exceptionMessage}};var b=function(e){this._conn=e,this._logger=e._logger};b.prototype.pollInterval=1e3,b.prototype.pollTimeout=1e4,b.prototype._request=function(e,t){var n=this._conn;e=s.clone(e);var r=[n.instanceUrl,"services/async",n.version].join("/");e.url=r+e.path;var o={responseType:e.responseType};return delete e.path,delete e.responseType,new d(this._conn,o).request(e).thenCall(t)},b.prototype.load=function(e,t,n,r,o){var i=this;if(!e||!t)throw new Error("Insufficient arguments. At least, 'type' and 'operation' are required.");s.isObject(n)&&n.constructor===Object||(o=r,r=n,n=null);var a=this.createJob(e,t,n);a.once("error",function(e){u&&u.emit("error",e)});var u=a.createBatch(),c=function(){u=null,a.close()},h=function(e){"PollingTimeout"!==e.name&&c()};return u.on("response",c),u.on("error",h),u.on("queue",function(){u.poll(i.pollInterval,i.pollTimeout)}),u.execute(r,o)},b.prototype.query=function(e){var t=e.replace(/\([\s\S]+\)/g,"").match(/FROM\s+(\w+)/i);if(!t)throw new Error("No sobject type found in query, maybe caused by invalid SOQL.");var n=t[1],r=this,o=new c.Parsable,i=o.stream("csv");return this.load(n,"query",e).then(function(e){var t=e.map(function(e){return r.job(e.jobId).batch(e.batchId).result(e.id).stream()});a(t).pipe(i)}).fail(function(e){o.emit("error",e)}),o},b.prototype.createJob=function(e,t,n){return new p(this,e,t,n)},b.prototype.job=function(e){return new p(this,null,null,null,e)},u.on("connection:new",function(e){e.bulk=new b(e)}),t.exports=b}).call(this,e("_process"))},{_process:2}],2:[function(e,t,n){function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===r||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function s(e){if(p===clearTimeout)return clearTimeout(e);if((p===o||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){m&&d&&(m=!1,d.length?b=d.concat(b):y=-1,b.length&&u())}function u(){if(!m){var e=i(a);m=!0;for(var t=b.length;t;){for(d=b,b=[];++y<t;)d&&d[y].run();y=-1,t=b.length}d=null,m=!1,s(e)}}function c(e,t){this.fun=e,this.array=t}function h(){}var l,p,f=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:r}catch(e){l=r}try{p="function"==typeof clearTimeout?clearTimeout:o}catch(e){p=o}}();var d,b=[],m=!1,y=-1;f.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];b.push(new c(e,t)),1!==b.length||m||i(u)},c.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=h,f.addListener=h,f.once=h,f.off=h,f.removeListener=h,f.removeAllListeners=h,f.emit=h,f.prependListener=h,f.prependOnceListener=h,f.listeners=function(e){return[]},f.binding=function(e){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(e){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}]},{},[1])(1)});
//# sourceMappingURL=jsforce-api-bulk.min.js.map