### Install Jsforce
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/top/node-example.html.md
Install the Jsforce library using npm before running the example.
```shell
$ npm install jsforce
```
--------------------------------
### Full Bulk Loading Flow Example
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/bulk.html.md
An interactive example demonstrating the complete process of bulk loading records, including job creation, batch execution, event handling, and polling.
```javascript
/* @interactive */
// Provide records
const accounts = [
{ Name : 'Account #4' },
{ Name : 'Account #6' },
{ Name : 'Account #7' },
];
// Create job and batch
const job = conn.bulk.createJob("Account", "insert");
const batch = job.createBatch();
// start job
batch.execute(accounts);
// listen for events
batch.on("error", function(batchInfo) { // fired when batch request is queued in server.
console.log('Error, batchInfo:', batchInfo);
});
batch.on("queue", function(batchInfo) { // fired when batch request is queued in server.
console.log('queue, batchInfo:', batchInfo);
batch.poll(1000 /* interval(ms) */, 20000 /* timeout(ms) */); // start polling - Do not poll until the batch has started
});
batch.on("response", (rets) => { // fired when batch finished and result retrieved
for (let 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(', ')}`);
}
}
// ...
});
```
--------------------------------
### Install jsforce CLI
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/top/cli-example.html.md
Install the jsforce CLI globally using npm. This is a prerequisite for using the command-line interface.
```shell
$ npm install -g jsforce
```
--------------------------------
### Making a GET Request
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/request.html.md
Use `Connection.request()` with a string URL for GET requests. This example fetches object information.
```javascript
/* @interactive */
const res = await conn.request('/services/data/v47.0/ui-api/object-info');
console.log(res)
```
```javascript
const res = await conn.request('/services/data/v47.0/ui-api/object-info');
console.log(res)
```
--------------------------------
### Package Directory Structure Example
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md
Illustrates the expected structure of a local package directory for deployment, which must include a package.xml file at its root.
```bash
tree ./package -L 1 -F
./package
├── classes/
├── objects/
├── package.xml
├── staticresources/
└── triggers/
```
--------------------------------
### Install JSforce Metadata Tools Globally
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md
Install the JSforce metadata tools globally via npm to make the `jsforce-deploy` and `jsforce-retrieve` commands available in your system's PATH.
```bash
$ npm install -g jsforce-metadata-tools
```
--------------------------------
### Install JSforce 2.0 Alpha
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20191216-jsforce20-alpha-preview-with-schema-type-feature.html.md
Install the latest alpha version of JSforce globally using npm.
```bash
$ npm i -g jsforce@alpha
```
--------------------------------
### Basic HTML Setup for Highlight.js
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/files/asset/highlight/README.md
Include the Highlight.js library and a stylesheet, then initialize highlighting on page load. This targets code blocks within `
` tags.
```html
```
--------------------------------
### Booting JSforce REPL with CoffeeScript Option
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md
Start the JSforce REPL with the `--coffee` option to use CoffeeScript, which offers a more concise syntax for writing JavaScript code.
```bash
$ jsforce --coffee
coffee>
```
--------------------------------
### Describe All Tooling Objects
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/tooling.html.md
Explains how to get a description of all tooling objects in the organization using `conn.tooling.describeGlobal()`.
```APIDOC
## Describe Tooling Objects
Describing all tooling objects in the organization is done by calling `Tooling.describeGlobal()`.
```javascript
/* @interactive */
const res = await conn.tooling.describeGlobal()
console.log(`Num of tooling objects : ${res.sobjects.length}`);
```
```
--------------------------------
### Data Migration: Query from Org1 to Org2
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/advanced.html.md
Illustrates a basic data migration setup where records are queried from one Salesforce connection and piped to a bulk insert job in another connection.
```javascript
//
// Connection for org which migrating data from
//
const conn1 = new jsforce.Connection({
// ...
});
//
// Connection for org which migrating data to
//
const conn2 = new jsforce.Connection({
// ...
});
//
// Get query record stream from Connetin #1
// and pipe it to batch record stream from connection #2
//
const query = await conn1.query("SELECT Id, Name, Type, BillingState, BillingCity, BillingStreet FROM Account");
const job = conn2.bulk.createJob("Account", "insert");
const batch = job.createBatch();
query.pipe(batch);
batch.on('queue', () => {
jobId = job.id;
batchId = batch.id;
//...
})
```
--------------------------------
### Query-and-Update/Destroy using Bulk V2 API
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/v2-bulk.html.md
This example shows how to perform update or delete operations on queried records, with an option to leverage the Bulk V2 API for large result sets.
```APIDOC
## Query-and-Update/Destroy using Bulk V2 API
### Description
This functionality allows you to query records and then perform update or delete operations on them. For large query results, it can automatically switch to using the Bulk API (including Bulk V2) to handle the operations efficiently.
### Method
`conn.sobject(objectName).find(query).destroy(options)` or `conn.sobject(objectName).find(query).update(data, options)`
### Parameters
#### `find` parameters
- **query** (Object) - The SOQL query criteria.
#### `destroy` or `update` options
- **allowBulk** (boolean) - Optional - If true, allows the operation to use the Bulk API for large result sets (default: false).
- **bulkThreshold** (number) - Optional - The number of queried records that triggers the switch to the Bulk API (default: 200).
- **bulkApiVersion** (number) - Optional - Specifies the Bulk API version to use (e.g., 2 for Bulk V2 API). Defaults to 1.
### Request Example
```javascript
// Example for destroying records queried today using Bulk V2 API
const rets = conn.sobject('Account')
.find({ CreatedDate: jsforce.Date.TODAY })
.destroy({
allowBulk: true, // allow using bulk API
bulkThreshold: 200, // when the num of queried records exceeds this threshold, switch to Bulk API
bulkApiVersion: 2 // use Bulk V2 API (default: 1)
});
for (const ret of rets) {
console.log('id: ' + ret.id + ', success: ' + ret.success);
}
```
### Response
#### Success Response
- **id** (string) - The ID of the record affected by the operation.
- **success** (boolean) - Indicates if the operation was successful for the record.
```
--------------------------------
### Describe SObject Metadata (Connection Method)
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/describe.html.md
Fetches SObject metadata using `Connection.describe()` or `Connection.describeSObject()`. This provides an alternative way to get SObject metadata directly from the connection object.
```APIDOC
## Describe SObject Metadata (Connection Method)
### Description
Fetches detailed metadata for a specific Salesforce SObject using the connection object.
### Method
`conn.describe(sobjectType)` or `conn.describeSObject(sobjectType)`
### Parameters
- **sobjectType** (string) - Required - The API name of the SObject (e.g., 'Account').
### Request Example
```javascript
const meta = await conn.describe('Account')
console.log(`Label : ${meta.label}`);
console.log(`Num of Fields : ${meta.fields.length}`);
```
### Response
- **label** (string) - The display label of the SObject.
- **fields** (array) - An array of field metadata objects.
```
--------------------------------
### Execute Bulk Batch and Handle Queue Event
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/bulk.html.md
Execute a batch with the prepared records and listen for the 'queue' event to get batch and job IDs.
```javascript
batch.execute(accounts);
batch.on("queue", (batchInfo) => { // fired when batch request is queued in server.
console.log('batchInfo:', batchInfo);
batchId = batchInfo.id;
jobId = batchInfo.jobId;
// ...
});
```
--------------------------------
### Create Records with Custom HTTP Headers
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/crud.html.md
This example shows how to pass custom HTTP headers, such as 'Sforce-Duplicate-Rule-Header', to a CRUD operation. This allows for advanced control over API behavior, like managing duplicate rules.
```javascript
const rets = await conn.sobject('Account')
.create(
accounts,
{
allowRecursive: true,
headers: {
'Sforce-Duplicate-Rule-Header': 'allowSave=true'
}
}
);
```
--------------------------------
### Node.js Usage of Highlight.js
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/files/asset/highlight/README.md
Use Highlight.js in a Node.js environment by installing it via NPM. You can highlight code with a known language or let the library auto-detect the language.
```javascript
var hljs = require('highlight.js');
// If you know the language
hls.highlight(lang, code).value;
// Automatic language detection
hls.highlightAuto(code).value;
```
--------------------------------
### Register OAuth2 client information in JSforce REPL
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md
This command starts an interactive wizard to register your OAuth2 client details, such as client ID, client secret, and redirect URI, within the JSforce REPL configuration.
```bash
> .register
Input client ID (consumer key) : 3MVG9A2kN3....bhT
Input client secret (consumer secret) : 21864....158
Input redirect URI : http://localhost:34321/oauth2/callback
Input login URL (default is https://login.salesforce.com) :
Client registered successfully.
>
```
--------------------------------
### Manual Highlight.js Initialization with jQuery
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/files/asset/highlight/README.md
Manually initialize highlighting for code blocks using `highlightBlock` function, especially useful for dynamically inserted content or custom markup. This example uses jQuery to select and highlight elements.
```javascript
$(document).ready(function() {
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});
```
--------------------------------
### Deploying with Username and Password
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md
Basic deployment using username and password credentials, specifying the local directory containing the package. Ensure the directory has a package.xml file.
```bash
$ jsforce-deploy -u username@example.org -p password123 -D ./package
```
--------------------------------
### Get Resource Information
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/chatter.html.md
Retrieves information for a specified Chatter resource using its path. This method is useful for getting details about users or other Chatter entities.
```APIDOC
## Get Resource Information
### Description
Retrieves information for a specified Chatter resource using its path. This method is useful for getting details about users or other Chatter entities.
### Method
GET (implicitly via `Chatter-Resource#retrieve()`)
### Endpoint
`/services/data/vX.X/chatter/{path}` or site-root relative path or absolute URI
### Parameters
#### Path Parameters
- **path** (string) - Required - The relative or absolute path to the Chatter resource.
### Request Example
```javascript
const res = await conn.chatter.resource('/users/me').retrieve();
console.log(`username: ${res.username}`);
console.log(`email: ${res.email}`);
console.log(`small photo url: ${res.photo.smallPhotoUrl}`);
```
### Response
#### Success Response (200)
- **username** (string) - The username of the user.
- **email** (string) - The email address of the user.
- **photo** (object) - Contains URLs for different sizes of the user's photo.
- **smallPhotoUrl** (string) - URL for the small version of the user's photo.
```
--------------------------------
### jsforce-deploy Help Options
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md
Displays all available options for the jsforce-deploy command. Use this to understand the full range of functionalities.
```bash
$ jsforce-deploy --help
```
--------------------------------
### Create and Connect to a Scratch Org using JSforce
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20170629-salesforce-dx-with-jsforce.html.md
This script demonstrates establishing a connection to a developer hub, creating a new scratch org, and then connecting to the created scratch org. Ensure you have registered a connected application to obtain the necessary client ID and secret.
```javascript
import fs from 'fs';
import jsforce from 'jsforce';
/**
*
*/
async function startScratchOrg(username, password, options) {
// establish oauth2 connection to dev hub org using jsforce
const hubConn = new jsforce.Connection({ ...options, version: '40.0' });
const hubUserInfo = await hubConn.login(username, password);
const hubUser = await hubConn.sobject('User').findOne({ Id: hubUserInfo.id }, 'Id,Username,Email');
console.log(`Connected to developer hub org: username = ${hubUser.Username}`);
const ScratchOrgInfo = hubConn.sobject('ScratchOrgInfo');
try {
await ScratchOrgInfo.describe();
} catch (e) {
throw new Error('Dev hub org is not enabled for this connection');
}
// create scratch org
console.log('Creating scratch org....');
const { id, success, errors } = await ScratchOrgInfo.create({
Country: 'JP',
Edition: 'Developer',
OrgName: 'testorg',
AdminEmail: hubUser.Email,
ConnectedAppConsumerKey: options.clientId,
ConnectedAppCallbackUrl: options.redirectUri,
});
if (!success) {
console.error(errors);
throw new Error('Error occurred while creating scratch org');
}
const orgInfo = await ScratchOrgInfo.retrieve(id);
console.log(`New scratch org has been created. ${orgInfo.Name}`);
// establish connection
const loginUrl = `https://${orgInfo.SignupInstance}.salesforce.com`;
const conn = new jsforce.Connection({ ...options, loginUrl });
const userInfo = await conn.authorize(orgInfo.AuthCode);
const user = await conn.sobject('User').findOne({ Id: userInfo.id });
console.log(`Connected with scratch org: username = ${user.Username}`);
// package deployment / data loading tasks from here
// ...
}
startScratchOrg('admin@devhub.example.org', 'passw0rd', {
// you should obtain client id / secret by registering a connected application
clientId: 'yyyyyyyyyyyyy',
clientSecret: 'xxxxxx',
redirectUri: 'http://localhost/callback',
});
```
--------------------------------
### Deploy Salesforce Package using Command Line
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md
Use this command to deploy a Salesforce package from a local directory. Ensure you provide valid username, password, and the package directory path.
```bash
$ jsforce-deploy -u admin@example.org -p password123 -D ./path/to/packageDir
```
--------------------------------
### Get Recently Used Reports
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/analytics.html.md
Lists recently accessed reports. Use this to quickly access reports the user has interacted with.
```javascript
/* @interactive */
// get recent reports
const res = await conn.analytics.reports()
for (const report of res) {
console.log(report.id)
console.log(report.name)
}
```
--------------------------------
### Conditional Queries with OR
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/query.html.md
Define multiple `AND`/`OR` conditional expressions by passing them in an array to the `find` method. This example demonstrates an `OR` condition using `$or`.
```javascript
// The following code gets translated to this soql query:
// SELECT Name FROM Contact WHERE LastName LIKE 'A%' OR LastName LIKE 'B%'
//
const contacts = await conn.sobject("Contact")
.find({
$or: [{ LastName: { $like : 'A%' }}, { LastName: { $like : 'B%'} }]
}, ['Name'])
console.log(contacts);
```
--------------------------------
### Get Recently Used Reports
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/analytics.html.md
Lists recently accessed reports. The response contains an array of report objects, each with an 'id' and 'name'.
```APIDOC
## Get Recently Used Reports
### Description
Lists recently accessed reports.
### Method
`conn.analytics.reports()`
### Response Example
```json
[
{
"id": "00Oxxxxxxxxxxxx",
"name": "Report Name"
}
]
```
```
--------------------------------
### Deploy Metadata from File
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/metadata.html.md
Deploy metadata components from a zip file to Salesforce. The deploy method accepts a readable stream for the zip file and deployment options.
```javascript
const fs = require('fs');
const zipStream = fs.createReadStream("./path/to/MyPackage.zip");
const result = await conn.metadata.deploy(zipStream, { runTests: [ 'MyApexTriggerTest' ] }).complete();
console.log('done ? :' + result.done);
console.log('success ? : ' + result.true);
console.log('state : ' + result.state);
console.log('component errors: ' + result.numberComponentErrors);
console.log('components deployed: ' + result.numberComponentsDeployed);
console.log('tests completed: ' + result.numberTestsCompleted);
```
--------------------------------
### Get all job results
Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/v2-bulk.html.md
This snippet explains how to retrieve all results from a completed Bulk V2 job, including successful, failed, and unprocessed records.
```APIDOC
## Get all job results
### Description
After a Bulk V2 job has finished processing, you can retrieve all the results, categorized into successful, failed, and unprocessed records.
### Method
`job.getAllResults()`
### Response
#### Success Response
- **successfulResults** (Array