Coder Social home page Coder Social logo

jsforce / jsforce Goto Github PK

View Code? Open in Web Editor NEW
1.3K 74.0 527.0 64.21 MB

Salesforce API Library for JavaScript applications (both on Node.js and web browser)

Home Page: http://jsforce.github.io/

License: MIT License

JavaScript 99.82% HTML 0.06% Apex 0.12% Shell 0.01% Procfile 0.01%
salesforce jsforce

jsforce's Introduction

jsforce

Salesforce API Library for JavaScript applications (both on web browser and Node.js)

CircleCI

Overview

JSforce (f.k.a. Node-Salesforce) is an isomorphic JavaScript Library utilizing Salesforce's API: It works both in the browser and with Node.js.

It capsulates the access to various APIs provided by Salesforce in asynchronous JavaScript function calls.

It also has command line interface (CLI) which gives interactive console (REPL), so you can learn the usage without hassle.

Supported Salesforce APIs are the following:

  • REST API (SOQL, SOSL, describe, etc.)
  • Apex REST
  • Analytics API
  • Bulk API
  • Chatter API
  • Metadata API
  • SOAP API
  • Streaming API
  • Tooling API

Documentation

See documentation in http://jsforce.github.io/ .

Releases

See Releases.

License

See license (MIT License).

Authors

Notes

If you have any questions first file it on issues before contacting authors via e-mail.

Tests

In order to run tests you will need a Salesforce Developer Org

You will also need to install the JsforceTestSuite package, which can be done by running:

SF_USERNAME=myusername SF_PASSWORD=password+securityToken ./test/bin/org-setup

You may need to run this more then once if you encounter timeouts or dropped connections/

Finally, to run the tests simply do:

SF_USERNAME=myusername SF_PASSWORD=password+securityToken npm run test:node

SF_USERNAME=myusername SF_PASSWORD=password+securityToken npm run test:browser

Contributions

Your contributions are welcome: both by reporting issues on GitHub issues or pull-requesting patches.

If you want to implement any additional features, to be added to JSforce to our master branch, which may or may not be merged please first check current opening issues with milestones and confirm whether the feature is on road map or not.

If your feature implementation is brand-new or fixing unsupposed bugs in the library's test cases, please include addtional test codes in the test/ directory.

jsforce's People

Contributors

acrosman avatar amphro avatar aotimme avatar cristiand391 avatar davidknoll avatar dependabot[bot] avatar frankzimper avatar greenkeeperio-bot avatar guanzhijie avatar jasonparekh avatar jesperkristensen avatar jgellin-sf avatar joeferraro avatar lilawren avatar mars avatar mdonnalley avatar michaelstuder avatar moonejon avatar mshanemc avatar nateferrero avatar nitnekb avatar pawelrychlik avatar pcon avatar scolladon avatar stanlemon avatar stemail23 avatar stomita avatar tedjt avatar tnoonan-salesforce avatar vuza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsforce's Issues

Describe call not working when connection established using access token

Error message: { [NOT_FOUND: The requested resource does not exist] name: 'NOT_FOUND', errorCode: 'NOT_FOUND' }

This happens when establishing a connection using the:
new jsforce.Connection({accessToken: xxx, instanceUrl: xxx})

However, the call works when establishing a connection using the:
conn.login(username, password, cb)

Problem with Bulk update 0 objects.

Hello,

there seems to be a problem with bulk update operation, when UPDATE condition matches 0 objects.
If I try to bulk update Accounts with condition i.e.:

    "query": {
        "xy_updated_on__c": {
            "$lt": "2014-09-16T05:48:05.000+0000"
        }
    }

and if there aren't any Accounts with field xy_updated_on__c lesser then "2014-09-16T05:48:05.000+0000", it returns an error "Unable to find any data to create batch" with error code 403 - it's okay.

But when I call the same query again, the callback function isn't being called and therefore no response is returned :-(.

conn.sobject('Opportunity')
    .find({ 'Account.Name' : 'Salesforce.com' })
    .update({ CloseDate: '2013-08-31' }, function(err, rets) { // <----- function(err, rets)
      if (err) { return console.error(err); }
      console.log(rets); 
      // ...
    });

Malformed SOQL if .where() called with a list

Currently if you run:

conn.sobject('SomeObject')
  .select('*')
  .where({someKey: ['someValue']})

then you'll get a malformed SOQL query error because lib/soql-builder will generate

SELECT item1, item2 FROM tableName WHERE somekey = ('someValue')

Normally when supplying a list to .where() it should be called with the $in operator but in cases where it is not we shouldn't create a malformed query. This issue comes up when using jsforce along with waterline because of how associations work.

Metadata#retrieve(options) examples

Could you please provide an example on how to use the Metadata#retrieve(options)? Assuming I have a manifest file (e.g. package.xml), how do I tell the Metadata#retrieve(options) to retrieve the metadata based on the package.xml? I'm not quite sure what the packageNames stands for in the request options { packageNames: [ 'My Test Package' ] }.

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>MyCustomObject__c</members>
        <name>CustomObject</name>
    </types>
    <types>
        <members>*</members>
        <name>CustomTab</name>
    </types>
    <types>
        <members>Standard</members>
        <name>Profile</name>
    </types>
    <version>30.0</version>
</Package>

Thanks in advance!

obs: You could label this as question and not a issue.

support for assignment rule headers

I'd like to update objects without triggering assignment rules. Typically I would do that using Assignment Rule headers, but I don't see support in jsforce for setting the SForce-Auto-Assign request header, or really any custom headers .

It seems like a fairly major change to plum support for extra headers into all the sobject and connection prototype methods. I've done that locally but am wondering what the best thing to do for a PR is? My solution was to change signature from

update(records, callback) to update(records, callback, options)

and options is a kitchen sink like

{
  extraHeaders: {
    SForce-Auto-Assign: 'FALSE'
  }
}

conn.identity getting stuck?

Given the following example:

app.get('/test', function(req, res) {
  async.mapSeries(myOauthArray, doStuff, function(err, results){
    console.log(results);
  });
});

function doStuff(oauthDetails, callback) {
  var conn = new jsforce.Connection(oauthDetails);
  conn.identity(function(err, result) {
    if (err) { callback(err, null) }
    callback(null, result.username);
  });
}

Where myOauthArray is an array of oauth2 credentials, i.e.:

[{
  oauth2 : {
    clientId : '<your Salesforce OAuth2 client ID is here>',
    clientSecret : '<your Salesforce OAuth2 client secret is here>',
    redirectUri : '<your Salesforce OAuth2 redirect URI is here>'
  },
  instanceUrl : '<your Salesforce server URL (e.g. https://na1.salesforce.com) is here>',
  accessToken : '<your Salesforrce OAuth2 access token is here>',
  refreshToken : '<your Salesforce OAuth2 refresh token is here>'
},
{
  oauth2 : {
    clientId : '<your Salesforce OAuth2 client ID is here>',
    clientSecret : '<your Salesforce OAuth2 client secret is here>',
    redirectUri : '<your Salesforce OAuth2 redirect URI is here>'
  },
  instanceUrl : '<your Salesforce server URL (e.g. https://na1.salesforce.com) is here>',
  accessToken : '<your Salesforrce OAuth2 access token is here>',
  refreshToken : '<your Salesforce OAuth2 refresh token is here>'
}]

The code successfully runs the first time I load /test, but it freezes without errors at any subsequent run, forcing me to restart the node app.

If I change the conn.identity with a simple conn.query, e.g.:

app.get('/test', function(req, res) {
  async.mapSeries(myOauthArray, doStuff, function(err, results){
    console.log(results);
  });
});

function doStuff(oauthDetails, callback) {
  var conn = new jsforce.Connection(oauthDetails);
  conn.query("SELECT count() FROM Account", function(err, result) {
    if (err) { callback(err, null) }
    callback(null, result.totalSize);
  });
}

Loading /test will now work fine every time.

What am I missing?

Set sandbox or loginUrl for cli

I did not see a way to define that a login call is for a sandbox for the cli interface. Would be nice to have a --loginUrl method or a --sandbox flag that uses https://test.salesforce.com instead.

nodewebkit

Hello

I'm trying to execute jsforce from node - webkit (https://github.com/rogerwang/node-webkit) trying to create a desktop web app using SalesForce.

The library seems to be installed correctly inside the project folder using npm command.

This is the error that I'm getting executing the following code:

var jsforce = require('jsforce');
var conn = new jsforce.Connection();

conn.login('xxxx@xxxxx', 'xxxxxxxxxxxxxxxxxxx', function(err, res) {
if (err) { return console.error(err); }

conn.query('SELECT Id, Name FROM Account', function(err, res) {
if (err) { return console.error(err); }
console.log(res);
});
});

Error:

Uncaught node.js Error

ReferenceError: XMLHttpRequest is not defined
at module.exports (C:\GUI2\node_modules\jsforce\lib\browser\request.js:4:17)
at createRequest (C:\GUI2\node_modules\jsforce\lib\transport.js:65:13)
at promise.then (C:\GUI2\node_modules\jsforce\lib\transport.js:30:5)
at Connection.loginBySoap (C:\GUI2\node_modules\jsforce\lib\connection.js:947:6)
at Connection.login (C:\GUI2\node_modules\jsforce\lib\connection.js:869:17)
at eval (file:///C:/GUI2/index.html:8:6)

Any clue or example that we would use?
would you reply me to [email protected]

Thanks

describeMetadata timing out

I'm using the metadata describe method with Node.js to attempt to return all the metadata from a fresh developer salesforce instance and no result is ever returned. The API call just times out after about 30 seconds. Whereas ANT will return a result within 2 seconds. Any idea why this is happening?

app.get('/', function(req, res, next) {
    console.log('Retrieving salesforce metadata...');
    // describe org metadata
    conn.metadata.describe(function(err, describeResult) {
        if(err) return console.log(err);

        console.log(describeResult);

        res.json(describeResult);
    });
});

Here is the console output, as you can see the GET request times out:

Retrieving salesforce metadata...
GET / - - ms - -

metadata deploy not supported in browsers

I am retrieving (successfully) zipped metadata, modifying it, and then trying to redeploy it -- all from a browser. I can retrieve and modify the metadata XML files, but when I then try to redeploy it in zip format, it fails because the Metadata.deploy function depends on the zipInput parameter being either a Stream or a Buffer. Both of these seem to be Node classes that aren't available in the browser. It would be great if the deploy method allowed zip input as a base64 encoded string as well. This would remove all Node dependencies.

HTTP Proxy

How can I setup a HTTP proxy to access the salesforce login url from within a company organization? I'm currently getting the following:

Error: connect ETIMEDOUT

Example:

var jsforce = require('jsforce');
var conn = new jsforce.Connection({
    proxy: 'http://proxy_ur:port'
});

Streaming API connections using OAuth

I'm unable to subscribe to topics using OAuth based connections unless I perform a query first.

The following code never gets a message:

var salesforceConnection = new jsforce.Connection({
    instanceUrl: salesforceInstanceUrl,
    oauth2: {
        clientId: salesforceClientId,
        clientSecret: salesforceClientSecret,
        loginUrl: salesforceLoginUrl
    },
    refreshToken: salesforceRefreshToken
});

salesforceConnection.streaming.topic('Topic').subscribe(function(message) {
    console.log(message);
});

The following is my workaround:

var salesforceConnection = new jsforce.Connection({
    instanceUrl: salesforceInstanceUrl,
    oauth2: {
        clientId: salesforceClientId,
        clientSecret: salesforceClientSecret,
        loginUrl: salesforceLoginUrl
    },
    refreshToken: salesforceRefreshToken
});

salesforceConnection.describe('Custom__c', function() {
    salesforceConnection.streaming.topic('Topic').subscribe(function(message) {
        console.log(message);
    });
});

resetPassword() and setPassword()

Is there any chance to add both conn.resetPassword(ID userID); and conn.setPassword(ID userID, string password); to jsforce?

Please do let me know if there's already a way to achieve this thorugh the current version.

Is it possible to use JSforce in angular ?

Hi ,
I would like to use JSforce in a browser mode in angularjs ,But it look like the native code do not allow it,
in the client class , the function "checkCallbackResponse" is using "window.location.hash" which make it impossible to work with angular.
Do you have any workaround ?
Thanks .
Idan

requests not always calling callback

I'm experiencing some issues whereby some jsforce requests are never invoking the callback. I've tracked the issue to the old version of the "request" library used in jsforce, and my testing suggests that updating to the current version of this library resolves the issues. I have not been able to prove it conclusively, but I believe that the 2.12.x version of the "request" library is incompatible with the node 0.10 streams2 implementation and is not invoking resume() correctly for this newer node release.

Cannot create connection on Windows

Code:

var jsforce = require('jsforce')
  , conn = jsforce.Connection();

Result:

D:\www\hc\node_modules\jsforce\lib\connection.js:142
  this.initialize(options);
       ^
TypeError: Object #<Object> has no method 'initialize'
    at Object.module.exports [as Connection] (D:\www\hc\node_modules\jsforce\lib\connection.js:142:8)
    at Object.<anonymous> (D:\www\hc\app.js:2:20)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

how to set bulk api batch size ?

I was trying to use the bulk api function to insert around 500,000 records and the size of the csv file is around 186 mb.
I used the example from the document ,

  var csvFileIn = fs.createReadStream("Installedproduct.csv");
    conn.bulk.load("customobject__c", "insert", csvFileIn, function(err, rets) {
      if (err) { return console.error(err); }
      for (var i=0; i < rets.length; i++) {
        if (rets[i].success) {
          console.log("#" + (i+1) + " loaded successfully, id = " + rets[i].id);
        } else {
          console.log("#" + (i+1) + " error occurred, message = " + rets[i].errors.join(', '));
        }
      }
    });

and the error I get is

{ [Error: Failed to read request. Exceeded max size limit of 10000000] name: undefined, code: 'ClientInputError' }

It might be related to the batch size, is there a way to specify the batch size in the load function of bulk api ?

Deceptive Default maxFetch

Query.prototype._maxFetch = 10000;

Without setting a maxFetch value, the library stops querying at 10,000 records. This is not documented anywhere, and we had no idea why salesforce stopped giving us records at this point. The default maxFetch should be infinite.

Using Streaming API from non-VF page through jsforce-ajax-proxy

tl;dr: Does JsForce's Streaming API work when using the "jsforce-ajax-proxy" proxy? JsForce is delegating the task to Faye, which doesn't use JsForce's Transport class, so I think this workflow isn't set up yet. Also, I don't know if the "jsforce-ajax-proxy" was designed to proxy messages from the streaming API.

Details:

I'm trying to use JsForce's Streaming API. I'm loading my app from localhost, using OAuth to get an access token, and then sending queries through JsForce. I had to set up a proxy using the jsforce-ajax-proxy, which works really great.

Now, I'm trying to use the streaming API, but I'm not sure it's possible when using the jsforce-ajax-proxy. I say that because I'm getting this error when Faye is trying to do that handshake. 405 Only POST allowed

Here's more info about the request which is being sent:

Request URL:https://na17.salesforce.com/cometd/30.0?message=%5B%7B%22channel%22%3A%22%2Fmeta%2Fhandshake%22%2C%22version%22%3A%221.0%22%2C%22supportedConnectionTypes%22%3A%5B%22callback-polling%22%5D%2C%22id%22%3A%221%22%7D%5D&jsonp=__jsonp1__
Request Method:GET
Status Code:405 Only POST allowed
Query String Parameters:message:[{"channel":"/meta/handshake","version":"1.0","supportedConnectionTypes":["callback-polling"],"id":"1"}]
jsonp:__jsonp1__

Because JsForce is delegating this task of doing the streaming to Faye, the requests sent by Faye won't use JsForce's Transport class, which is where the proxy given to JsForce is used. On top of that, I believe Bayeux protocol is a little complicated and requires server support, so maybe the "jsforce-ajax-proxy" isn't set up to handle JsForce's Streaming API.

Does anyone have info here?

a question on intercepting ETIMEDOUT

Hi,

Recently, I've been getting more and more timeouts from SF calls with jsforce (ETIMEDOUT errors from request.js). It doesn't have anything to do with jsforce, I assume it's SF's issues. So I'd like to be prepared for these situations - retry the operation in case it timed out. Obviously, I could do it with the callback function:

connection.sobject("Order").create(order, function(err, result) {
 // if err is a timeout then retry the whole call
});

But we use jsforce in a handful of places in the code - so I'd rather go with some generic solution to the problem - to cover not only "Order"s and not only "create"s.

I've spent some time playing around jsforce code looking here and there, but I didn't find any elegant and non-intrusive solution that would suit my needs (attaching error-event-handlers, enhancing the Connection/Query modules, writing an abstraction layer on top of jsforce.Connection, etc).

Would you have any ideas how to achieve that?

Node-phantom timeouts

In OAuth2 web authentication flow testing, node-phantom cannot handle and stuck in the middle of the test then timeouts.

Metadata-AsyncResultLocator#complete() no being called after successful operation

Metadata-AsyncResultLocator#complete() is not being after custom field has been successfully created.

 conn.metadata.create('CustomField', customFields).complete(err, res) {
console.log("I will be never called");
}

If I check the status with metadata.checkStatus I can clearly see that all the operations have been finished successfully.

batch api authorization error

Hi,

I'm able to use the metadata API without any problems from a VisualForce page. When I try to use the batch API (in the same page), however, I get the following error:
XMLHttpRequest cannot load https://na15.salesforce.com/services/async/30.0/job. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://c.na15.visual.force.com' is therefore not allowed access.

It seems the batch endpoint is in a different domain than the one I'm authenticating on (and using for the metadata API calls). Has anyone else experienced this? Is there a workaround?

JSForce is pretty awesome, btw.

Tooling#completions() fails

Raises following error:

UNKNOWN_EXCEPTION: An unexpected error occurred. Please include this ErrorId if you contact support: 179754945-35410 (-1975115202)
      at onResponse (/Users/stomita/Work/Salesforce/jsforce/lib/connection.js:330:13)
      at _fulfilled (/Users/stomita/Work/Salesforce/jsforce/node_modules/q/q.js:798:54)
      at self.promiseDispatch.done (/Users/stomita/Work/Salesforce/jsforce/node_modules/q/q.js:827:30)
      at Promise.promise.promiseDispatch (/Users/stomita/Work/Salesforce/jsforce/node_modules/q/q.js:760:13)
      at /Users/stomita/Work/Salesforce/jsforce/node_modules/q/q.js:574:44
      at flush (/Users/stomita/Work/Salesforce/jsforce/node_modules/q/q.js:108:17)
      at process._tickCallback (node.js:415:13)

Set field value to NULL with Bulk API doesn't work.

Hello!

I've found this amazing API a few weeks ago - it's very easy to use!
But yesterday, I've found a problem when updating some fields and setting field value to NULL. Using a standard API,

conn.sobject(params.object).update recordsForUpdate, (err, records) ->
    cb err, records

it works fine and the field's value is resetted to NULL. The problem is when I use JSForce bulk API to update lots of objects:

// UPDATE Opportunity 
// SET CloseDate = '2013-08-31'
// WHERE Account.Name = 'Salesforce.com'
conn.sobject('Opportunity')
    .find({ 'Account.Name' : 'Salesforce.com' })
    .update({ SomeCustomVield: null }, function(err, rets) { // <----- There is the NULL value. 
      if (err) { return console.error(err); }
      console.log(rets);
      // ...
    });

JSForce returns a response that the record was successfully updated, but it wasn't :-(.
Salesforce also provide some documentation about setting fields to NULL here: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_concepts_core_data_objects.htm
But unfortunately, this doesn't work with JSForce :-(.

Could somebody, please, help mi to use bulk API and update field value to a NULL?

Thanks

Pali

Mocking/Stubbing

Is there anyway to mock/stub a salesforce server so I can write tests that don't reach out to the network?

I'm currently using a stub API server via restify that simply returns stub responses, and pass that URL to the Connection constructor, (for stubbing my custom apexrest endpoints that live on salesforce servers) but I'm not quite clear what endpoints I need to mock in order to simulate the responses JSForce will receive when I execute SObject queries, for example.

metadata.list() returns without any response

conn.metadata.list('ReportFolder',31.0, function(err, result){
if(err) return console.log(err);
console.log('result :');
console.log(result);
});

This code, does not fire the callback.

Problem to download Document/Attachments

jsforce = require("jsforce")
conn = new jsforce.Connection({})
conn.login 'username', 'password', (err, userInfo) ->
return console.error(err) if err

# Now you can get the access token and instance URL information.
# Save them to establish connection next time.
console.log "Access Token: "+conn.accessToken
#console.log conn.instanceUrl

# logged in user property
console.log "User ID: " + userInfo.id
console.log "Org ID: " + userInfo.organizationId
fs = require "fs" 
fileOut = fs.createWriteStream('./test.pdf') 
docId = 'documentID' 
conn.sobject('Document').record(docId).blob('Body').pipe(fileOut)

Query Include SubQuery

Is there a specific way to use config.include in Query?

I think this is because config.include is passed into function Query.include.
https://github.com/jsforce/jsforce/blob/master/lib/query.js#L170

The documentation specifies that the first argument should be a string.
If is an object, it appears to enumerate through the object and call itself again and passing in the correct arguments.

This would suggest to me that I should make option.includes an object since enumerating through an array will have a lot of additional properties.

If I do, the program crashes at https://github.com/jsforce/jsforce/blob/master/lib/query.js#L170

because config.include is being treated like an array.

I cannot determine what the use of that line is as if I comment it out everything appears to function just fine.

As a workaround I had to to make config.include an object and define an non-enumerable property called "push" assigned to a blank function for it to work properly.

Refresh happening over and over

Hope this isn't pilot error. Super simple program:

conn.on ('refresh', function (accessToken, res) {
console.log ('New accces token = ' + accessToken);
});

conn.identity (function (err, res) {
console.log (res);
});

The connection setup is not shown. We have a bunch of users and we have their oAuth credentials stored away. It's no surprise that these credentials could be stale in some cases. JSforce is awesome; it auto-magically refreshes stale tokens. For 97 percent of users this code works fine. Some of them do see a single refresh event, as expected. But for three precent of the users, the refresh event fires continuously. It returns the same new token every time. The code never reaches the console.log () inside the conn.identity () call.

Using nForce.js we are not seeing the repeated refreshes.

Thanks in advance for any suggestions.

Describing an sobject describes all sbjects instead

if (fields1[f.name] && f.updateable && !f.custom && f.type !== 'reference') {

obj = conn.sobject('Account')
obj.describe().done((err, res) ->
res.fields

'fields' is always undefined, but in the example code you have some code that references this field. I'm trying to describe the sobject in order to get things like 'updateable', and sortable. 'res' is a huge json string of all objects, without fields.

lists function supports Array<ListMetadataquery> of size 3 only

var lstquery=[{
type:'CustomObject'
},
{
type:'Workflow'
},
{
type:'CustomField'
}
]

conn.metadata.list(lstquery2,function(error,res){
if (err) { return console.error(err); }
console.log(res);
});

works
but when i add another item to the lstquery,
var lstquery=[{
type:'CustomObject'
},
{
type:'Workflow'
},
{
type:'CustomField'
},
{type: 'ApexClass'}

    ]

it doesn't work.

Exceptions in Promise.then() fulfilled handler being swallowed

I'm having trouble with exceptions not being propagated. Perhaps it's something I'm not doing correctly, but the code seems pretty straightforward.

#!/usr/bin/env node

var jsforce = require('jsforce');

function fulfilled(result) {
    console.log('fulfilled', result);
    throw new Error('BOOM!');
}

function rejected(reason) {
    console.log('rejected', reason);
}

(function() {
    var user = process.argv[2],
        pass = process.argv[3],
        conn = new jsforce.Connection();
    conn.login(user, pass).then(fulfilled, rejected);
})();

When I run this using node script.js <user> <password+token> I get:

fulfilled { id: '005i0000002qatoAAA',
  organizationId: '00Di0000000kpRMEAY',
  url: 'https://login.salesforce.com/id/00Di0000000kpRMEAY/005i0000002qatoAAA' }

But no report of the exception being thrown. I would expect the exception to either (a) propagate out to the top level and be reported by Node (where I could catch it with a domain, or an uncaughtException handler), or be passed to the rejected handler, but neither is happening.

[Error: socket hang up] code: 'ECONNRESET'

From now and then depending on the number of requests made to create users(see below) I'm getting the following [Error: socket hang up] code: 'ECONNRESET' when I'm behind a HTTP proxy. I've made a few researches and it might be related to the fact where the request is not being closed (e.g. req.end()) or some request options you can provide to header (e.g. Content-Length).

conn.sobject("User").create(properties, function (err, result) {
  ...
});

Any clues?

promise callback in query should only be executed when the query ends

The Query promise is resolved on response. That means that writing something like this will not get all results, only the first page of results returned by Salesforce.

It seems more appropriate to call the promise progress callback on response and to resolve the promise on end. That way in then all results to the query are available.

conn.sobject(typeId).find(conditions, '*').run({autoFetch: true}).then(logResults);

function logResults(res) {
   // only first response here, not all records are available here
}

https://github.com/jsforce/jsforce/blob/master/lib/query.js#L378

Hitting result max when using too many query selectors

I'm running into an issue where a max of only 200 records are returned if several query selectors are being used. This is an issue for me since I'm selecting all attributes on the corresponding model within the ORM so that I don't get back every field from salesforce. The issue can be reproduced by using the all selector '*'. For example, assuming the Account object has 450 records:

// This query will return all 450 records.
conn.sobject('Account')
  .select('Id')
  .execute(function(err, res) {
    console.log('LEN: ' + res.length)
  })

// However, this query will only return 200 records
conn.sobject('Account')
  .select('*')
  .execute(function(err, res) {
    console.log('LEN: ' + res.length)
  })

I've ran the query directly against SFDC API using all of the model attributes and it returns all records for me so something may be causing this issue within jsforce. I also checked on what lib/connection.js is sending to the API and it seems to build the HTTP request just fine. It's possible that something is up with the post processing of the response body but I'm not entirely sure.

Throwing error in 'onResponse' causes program termination.

Description

I think throwing errors in callback of a Q promise is causing Q to throw an uncaught error thus terminating the application.

To reproduce, you can change this function:
https://github.com/jsforce/jsforce/blob/master/lib/connection.js#L279

...to make a new Error object and throw an error.

I encountered this because issues Salesforce were having with their DNS provider.
There is a root problem somewhere where a DNS resolve error is not bubbling up correctly.

Then this error is thrown, which is caught my Q and causes the program to terminate:
https://github.com/jsforce/jsforce/blob/master/lib/connection.js#L325

Background

Today Salesforce was having issues with its DNS provider.
(Click on the icon for current status https://trust.salesforce.com/trust/status/)
I noticed that jsforce threw up an interesting error around this time.

When I ran my app again it, it spit out a different error (getaddrinfo ENOTFOUND).
This error is for when a domain could not be resolved.
Additional testing confirmed that I couldn't resolve login.salesforce.com and other salesforce sub-domains properly in other tools.

Stacktrace

Authenticated and then Salesforce becomes unresolvable:

{ [Error] name: undefined, message: undefined }

./node_modules/q/q.js:126
                    throw e;
                          ^
Error
    at onResponse (./node_modules/jsforce/lib/connection.js:325:13)
    at ./node_modules/jsforce/lib/promise.js:51:12
    at _fulfilled (./node_modules/jsforce/node_modules/q/q.js:798:54)
    at self.promiseDispatch.done (./node_modules/jsforce/node_modules/q/q.js:827:30)
    at Promise.promise.promiseDispatch (./node_modules/jsforce/node_modules/q/q.js:760:13)
    at ./node_modules/jsforce/node_modules/q/q.js:574:44
    at flush (./node_modules/jsforce/node_modules/q/q.js:108:17)
    at process._tickCallback (node.js:415:13)

Salesforce is not resolvable and attempting to authenticate:

{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

./node_modules/q/q.js:126
                    throw e;
                          ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

Different session expired error on bulk load method vs normal crud

The field and code returned from the bulk API load method, http://jsforce.github.io/jsforce/doc/Bulk.html#load, when a session is expired is different than just calling the various CRUD endpoints. The bulk api json returned for an invalid session is {"code":"InvalidSessionId"}. While the json returned from a CRUD endpoint is returned as {"errorCode":"INVALID_SESSION_ID"}. Ideally these would be the same so client's can use the same logic to handle expired sessions.

Because Query is 'thennable' it can not be used to resolve a promise

I use promises quite a bit and am running into an issue where I'd like to resolve a promise with a Query instance. I'm not able to though because Query is 'thenable' and when then is executed during evaluation of the return values in the promise chain the query is executed and the resolution becomes the result of the query. This is blocking me from using the event/pipe capabilities of Query in my code.

Contrived example using when

when.resolve(connection)
    .then(function (c) {
      return c.sobject('Lead').find('*').limit(100);
    })
   .then(function (q) {
     // q will not be a Query here it will be the result of the executed query
   });

I think query should have a .promise getter or something that allows a 'thenable' associated with the query to be explicitly retrieved without query itself being 'thenable'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.