How to use jsforce - 10 common examples

To help you get started, we’ve selected a few jsforce examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / jsforce / jsforce-tests.ts View on Github external
console.log(`itemsLikeCreateResult['likedItem']: ${itemsLikeCreateResult as any['likedItem']}`);
}

(async () => {
    const query2: sf.QueryResult =
        await (salesforceConnection.query("SELECT Id, Name FROM User") as Promise>);
    console.log("Query Promise: total in database: " + query2.totalSize);
    console.log("Query Promise: total fetched : " + query2.records[0]);

    await testAnalytics(salesforceConnection);
    await testChatter(salesforceConnection);
    await testMetadata(salesforceConnection);
    await testExecuteAnonymous(salesforceConnection);
})();

const oauth2 = new sf.OAuth2({
    // you can change loginUrl to connect to sandbox or prerelease env.
    // loginUrl : 'https://test.salesforce.com',
    clientId: '',
    clientSecret: '',
    redirectUri: ''
});
oauth2.getAuthorizationUrl({ scope: 'api id web' });

const job = salesforceConnection.bulk.createJob("Account", "insert");
const batch = job.createBatch();
batch.execute(undefined);
batch.on("queue", (batchInfo) => { // fired when batch request is queued in server.
    console.log('batchInfo:', batchInfo);
    const batchId = batchInfo.id;
    const jobId = batchInfo.jobId;
});
github Plazmaz / leaky-repo / web / js / salesforce.js View on Github external
function sfQuery(queryString, success, error){
    let conn = new jsforce.Connection();
    // Security Risk!
    conn.login('username@example.com', 'salesforcepassword', function(err, res) {
        if (err) {
            error(err);
            console.error(err);
        }
        conn.query('SELECT Id FROM User', function(err, res) {
            if (err) {
                error(err);
                console.error(err);
            }
            success(res);
        });
    });
}
github wadewegner / sfdx-waw-plugin / commands / auth_username_login.js View on Github external
run(context) {
      const username = context.flags.username;
      const password = context.flags.password;
      let instanceUrl = context.flags.instanceurl;

      if (!instanceUrl) {
        instanceUrl = 'https://login.salesforce.com';
      }

      const saveAsDefault = false;

      const conn = new jsforce.Connection({
        // you can change loginUrl to connect to sandbox or prerelease env.
        loginUrl: instanceUrl
      });

      conn.login(username, password, (err, userInfo) => {
        if (err) {
          return console.error(err);
        }

        const orgSaveData = [];
        orgSaveData.orgId = userInfo.organizationId;
        orgSaveData.accessToken = conn.accessToken;
        orgSaveData.instanceUrl = conn.instanceUrl;
        orgSaveData.username = username;
        orgSaveData.loginUrl = instanceUrl;
github jsforce / jsforce-metadata-tools / lib / deploy.js View on Github external
'use strict';

var path = require('path');
var jsforce = require('jsforce');
var archiver = require('archiver');
var Promise = jsforce.Promise;
var connect = require('./connect');

var DEPLOY_OPTIONS =
  "allowMissingFiles,autoUpdatePackage,checkOnly,ignoreWarnings,performRetrieve,purgeOnDelete,rollbackOnError,runAllTests,runTests,singlePackage,testLevel".split(',');

/* @private */
function noop() {}

/**
 *
 */
function deployFromZipStream(zipStream, options) {
  var logger = options.logger || { log: noop };
  return connect(options).then(function(conn) {
    logger.log('Deploying to server...');
    conn.metadata.pollTimeout = options.pollTimeout || 60*1000; // timeout in 60 sec by default
github jsforce / jsforce-metadata-tools / lib / retrieve.js View on Github external
'use strict';

var decompress = require('decompress');
var fs = require('fs');
var fstream = require('fstream');
var path = require('path');
var stream = require('readable-stream');
var jsforce = require('jsforce');
var archiver = require('archiver');
var xml2js = require('xml2js');
var Promise = jsforce.Promise;
var connect = require('./connect');

var RETRIEVE_OPTIONS =
  "apiVersion,packageNames,singlePackage,specificFiles,unpackaged".split(',');

/* @private */
function noop() {}

/**
 *
 */
function retrieve(options) {
  var logger = options.logger || { log: noop };
  return connect(options).then(function(conn) {
    logger.log('Retrieving from server...');
    conn.metadata.pollTimeout = options.pollTimeout || 60*1000; // timeout in 60 sec by default
github douglascayers / sfdc-swag-level-platform-events-demo / app.js View on Github external
app.get( '/oauth2/callback', function( req, res ) {

    // in testing, browsers would send a duplicate request after 5 seconds
    // if this redirection did not respond in time.
    // to avoid having a duplicate request we must tell the browser to wait longer
    // https://github.com/expressjs/express/issues/2512
    req.connection.setTimeout( 1000 * 60 * 10 ); // ten minutes

    // initialize salesforce client for making the oauth authorization request
    var sfClient = new jsforce.Connection({
        oauth2 : sf_oauth2,
        version : process.env.SALESFORCE_API_VERSION
    });

    // salesforce oauth authorize request to get access token
    sfClient.authorize( req.query.code, function( err, userInfo ) {

        if ( err ) {

            handleError( err, res );

        } else {

            subscribeToEvents( sfClient, res );

        }
github wadewegner / sfdx-waw-plugin / src / commands / waw / auth / username / login.ts View on Github external
public async run(): Promise {
    const username = this.flags.username;
    let password = this.flags.password;
    let instanceUrl = this.flags.instanceurl;

    if (!instanceUrl) {
      instanceUrl = 'https://login.salesforce.com';
    }

    if (!password) {
      password = await this.ux.prompt(`password for ${username}`, { type: 'mask' });
    }

    const conn = new jsforce.Connection({
      // you can change loginUrl to connect to sandbox or prerelease env.
      loginUrl: instanceUrl
    });

    await conn.login(username, password);

    const accessTokenOptions = {
      accessToken: conn.accessToken,
      instanceUrl: conn.instanceUrl,
      loginUrl: instanceUrl,
      orgId: getString(conn, 'userInfo.organizationId')
    };

    const auth = await AuthInfo.create({ username, accessTokenOptions });
    await auth.save();
github gbockus / jsForceInAction / server / services / SalesforceService.js View on Github external
function getOAuth2() {
    return new jsforce.OAuth2({
      // you can change loginUrl to connect to sandbox or prerelease env.
      // loginUrl : 'https://test.salesforce.com',
      clientId: config.app.key,
      clientSecret: config.app.secret,
      redirectUri: config.app.callbackURL
    });
  }
github douglascayers / sfdc-swag-level-platform-events-demo / app.js View on Github external
// ==============================================
// Load libraries
// ==============================================

var dotenv   = require('dotenv').config();          // necessary if running via 'node app.js' instead of 'heroku local'
var jsforce  = require('jsforce');                  // salesforce client
var express  = require('express');                  // nodejs de-facto web server
var exphbs   = require('express-handlebars');       // for html templating responses
var path     = require('path');                     // utility for parsing and formatting file paths

// ==============================================
// Salesforce OAuth Settings (reusable)
// ==============================================

var sf_oauth2 = new jsforce.OAuth2({
    loginUrl : process.env.OAUTH_SALESFORCE_LOGIN_URL,
    clientId : process.env.OAUTH_SALESFORCE_CLIENT_ID,
    clientSecret : process.env.OAUTH_SALESFORCE_CLIENT_SECRET,
    redirectUri : process.env.OAUTH_SALESFORCE_REDIRECT_URI
});

// ==============================================
// Configure web app to respond to requests
// ==============================================

var app = express();

app.engine( 'handlebars', exphbs( { defaultLayout: 'main' } ) );

app.set( 'view engine', 'handlebars' );
app.set( 'json spaces', 4 ); // pretty print json
github eltoroit / ETCopyData / src / @ELTOROIT / Importer.ts View on Github external
return new Promise((resolve, reject) => {
			// DELETING
			Util.writeLog(`[${org.alias}] Deleting records from [${sObjName}]`, LogLevel.TRACE);
			org.conn.bulk.pollTimeout = org.settings.pollingTimeout;
			// LEARNING: Deleting sObject records in bulk
			org.conn.sobject(sObjName)
				.find({ CreatedDate: { $lte: Date.TOMORROW } })
				.destroy(sObjName)
				.then((results: RecordResult[]) => {
					let totalSuccess: number = 0;
					let totalFailures: number = 0;
					results.forEach((result: any) => {
						if (result.success) {
							totalSuccess++;
						} else {
							if ((result.errors.length === 1) && (result.errors[0] === "ENTITY_IS_DELETED:entity is deleted:--")) {
								// Ignore error
							} else {
								totalFailures++;
								msg = `*** [${org.alias}] Error deleting [${sObjName}] records. ${result.errors.join(", ")}`;
								Util.writeLog(msg, LogLevel.ERROR);
							}
						}

jsforce

Salesforce API Library for JavaScript

MIT
Latest version published 24 days ago

Package Health Score

86 / 100
Full package analysis