### 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) - An array of records that were successfully processed.
- **failedResults** (Array) - An array of records that failed to be processed, including error information.
- **unprocessedRecords** (Array) - An array of records that were not processed, which can be strings or objects.

#### Response Example
```javascript
const res = await job.getAllResults();

for (const rec of res.successfulResults) {
  console.log(`id = ${rec.sf__Id}, loaded successfully`);
}
for (const rec of res.failedResults) {
  console.log(`id = ${rec.sf__Id}, failed to load due to: ${rec.sf__Error}`);
}
for (const rec of res.unprocessedRecords) {
  if (typeof rec === 'string') {
    console.log(`Bad record: ${rec}`);
  } else {
    console.log(`unprocessed record: ${rec}`);
  }
}
```
```

--------------------------------

### Making a POST Request with JSON Body

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/request.html.md

For methods other than GET, pass an object to `Connection.request()`. The body must be serialized, and `content-type` set to `application/json`.

```javascript
/* @interactive */
// Bulk API 2.0 - Query
const requestBody = {
  operation: 'query',
  query: 'SELECT Id, Name FROM Account LIMIT 1000',
};

const res = await conn
  .request({
    method: 'POST',
    url: '/services/data/v47.0/jobs/query',
    body: JSON.stringify(requestBody),
    headers: {
      'content-type': 'application/json',
    },
  });
console.log(res)
```

--------------------------------

### jsforce CLI with Command-Line Arguments

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/top/cli-example.html.md

Execute a SOQL query directly from the command line using connection and query arguments. The output is in JSON format.

```shell
$ jsforce -c username@salesforce.example.org -e "query('SELECT Id, Name FROM Account LIMIT 2')"
{"totalSize":2,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v29.0/sobjects/Account/001i0000009PyDrAAK"},"Id":"001i0000009PyDrAAK","Name":"GenePoint"},{"attributes":{"type":"Account","url":"/services/data/v29.0/sobjects/Account/001i0000009PyDsAAK"},"Id":"001i0000009PyDsAAK","Name":"United Oil & Gas, UK"}]}

```

--------------------------------

### Bulk Delete from SOQL Query

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/crud.html.md

Perform a bulk delete operation starting from a SOQL query result by providing the sobject type to `Query.destroy()`.

```javascript
/* @interactive */
const rets = await conn.query("SELECT Id FROM Account WHERE CreatedDate = TODAY").destroy('Account');
console.log(rets);
```

--------------------------------

### Connect to Salesforce using username and password

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md

This snippet shows the basic command to connect to Salesforce using a username and password in the JSforce REPL. You will be prompted for your password.

```bash
$ jsforce
> .connect username@example.org
Password: *******
Logged in as: username@example.org
>
```

--------------------------------

### Execute SOQL query with callback

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md

This snippet demonstrates how to create an Account record using the `sobject` API with a traditional callback function to handle the response or errors.

```javascript
var debugOut = function(err, res) { if (err) { console.error(err); } else { console.log(res); } }; 
undefined
sobject('Account').create({ Name: 'My Test Account' }, debugOut);
```

--------------------------------

### Get Salesforce Authorization URL

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/oauth2.html.md

Use `OAuth2.getAuthorizationUrl(options)` to generate the Salesforce authorization URL. Ensure your OAuth2 client information is correctly configured.

```javascript
import { OAuth2 } from 'jsforce';

//
// OAuth2 client information can be shared with multiple connections.
//
const oauth2 = new OAuth2({
  // you can change loginUrl to connect to sandbox or prerelease env.
  // loginUrl : 'https://test.salesforce.com',
  clientId : '',
  clientSecret : '',
  redirectUri : ''
});
//
// Get authorization url and redirect to it.
//
app.get('/oauth2/auth', function(req, res) {
  res.redirect(oauth2.getAuthorizationUrl({ scope : 'api id web' }));
});
```

--------------------------------

### Deploying using a JSforce Connection Registry

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md

Leverages an existing JSforce connection stored in the registry, simplifying authentication by omitting the password if the connection is valid.

```bash
$ jsforce-deploy -c username@example.org -D ./package
```

--------------------------------

### jsforce-retrieve Command Help

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md

Displays the usage and available options for the jsforce-retrieve command.

```bash
$ jsforce-retrieve --help
```

--------------------------------

### Get User Information - Chatter API

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/chatter.html.md

Retrieve information for the current user using the Chatter API. Ensure you have authenticated with jsforce before calling this method.

```javascript
/* @interactive */
const res = await conn.chatter.resource('/users/me')
console.log(`username: ${res.username}`);
console.log(`email: ${res.email}`);
console.log(`small photo url: ${res.photo.smallPhotoUrl}`);
```

--------------------------------

### List Metadata Summary Information

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/metadata.html.md

Retrieves summary information for specified metadata types within an org. Useful for getting a quick overview of metadata components.

```javascript
/* @interactive */
const types = [{type: 'CustomObject', folder: null}];
const metadata = await conn.metadata.list(types, '60.0');
const meta = metadata[0]

console.log(`metadata count: ${metadata.length}`);
console.log(`createdById: ${meta.createdById}`);
console.log(`createdByName: ${meta.createdByName}`);
console.log(`createdDate: ${meta.createdDate}`);
console.log(`fileName: ${meta.fileName}`);
console.log(`fullName: ${meta.fullName}`);
console.log(`id: ${meta.id}`);
console.log(`lastModifiedById: ${meta.lastModifiedById}`);
console.log(`lastModifiedByName: ${meta.lastModifiedByName}`);
console.log(`lastModifiedDate: ${meta.lastModifiedDate}`);
console.log(`manageableState: ${meta.manageableState}`);
console.log(`namespacePrefix: ${meta.namespacePrefix}`);
console.log(`type: ${meta.type}`);
```

--------------------------------

### Connect to Salesforce using JSforce REPL

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20150816-jsforce15-released.html.md

Use the `.authorize` command in the JSforce REPL to establish an OAuth2 web server flow connection. The connection details are automatically stored for later use.

```bash
$ jsforce
> .authorize

... OAuth flow starts ...

Logged in as : user01@example.org
> .exit
```

--------------------------------

### Deploying to a Custom Login URL

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md

Use this command when your Salesforce instance is not on the default login URL. The --sandbox option can be used for test environments.

```bash
$ jsforce-deploy -u username@example.org -p password123 -l https://mydomain.my.salesforce.com -D ./package
```

--------------------------------

### Pipe and Map Contacts to CSV (Lower Level)

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/advanced.html.md

Achieves the same result as the previous Contact export example but uses the lower-level `.pipe(jsforce.RecordStream.map())` method for transformation.

```javascript
const fs = require('fs');
conn.sobject('Contact')
    .find({}, { Id: 1, Name: 1 })
    .pipe(jsforce.RecordStream.map((r) => {
      return { ID: r.Id, FULL_NAME: r.Name };
    }))
    .stream().pipe(fs.createWriteStream("Contact.csv"));

```

--------------------------------

### Retrieve Bulk Query Batch Results

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/bulk.html.md

Get batch result IDs for a known job and batch ID, then retrieve and stream individual results to CSV files.

```javascript
const fs = require('fs');
const batch = conn.bulk.job(jobId).batch(batchId);
batch.retrieve((err, results) => {
  if (err) { return console.error(err); }
  for (let i=0; i < results.length; i++) {
    var resultId = result[i].id;
    batch.result(resultId).stream().pipe(fs.createWriteStream('./result'+i+'.csv'));
  }
});
```

--------------------------------

### Get Collection Resource Information

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/chatter.html.md

Retrieves a collection of Chatter resources, allowing for filtering and pagination using query parameters. This is useful for searching or listing multiple items.

```APIDOC
## Get Collection Resource Information

### Description
Retrieves a collection of Chatter resources, allowing for filtering and pagination using query parameters. This is useful for searching or listing multiple items.

### Method
GET (implicitly via `Chatter-Resource#retrieve()`)

### Endpoint
`/services/data/vX.X/chatter/{path}` with query parameters

### Parameters
#### Path Parameters
- **path** (string) - Required - The relative or absolute path to the Chatter collection resource.

#### Query Parameters
- **q** (string) - Optional - Query string for filtering results.
- **offset** (integer) - Optional - The starting offset for the results.
- **limit** (integer) - Optional - The maximum number of results to return.
(Refer to Chatter REST API Guide for all acceptable query parameters)

### Request Example
```javascript
const result = await conn.chatter.resource('/users', { q: 'Suzuki' }).retrieve();
console.log("current page URL: " + result.currentPageUrl);
console.log("next page URL: " + result.nextPageUrl);
console.log("users count: " + result.users.length);

for (let i=0; i
  through2.obj (file, enc, callback) ->
    conn = new jsforce.Connection()
    conn.login username, password
    .then ->
      conn.metadata.deploy(file.contents).complete(details: true)
    .then (res) ->
      if res.details?.componentFailures
        console.error res.details?.componentFailures
        return callback(new Error('Deploy failed.'))
      callback()
    , (err) ->
      console.error(err)
      callback(err)
```

--------------------------------

### Describe SObject Metadata via Connection

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/describe.html.md

Fetches metadata for a specific SObject using the `Connection.describe()` method. This is an alternative to `SObject.describe()`.

```javascript
/* @interactive */
const meta = await conn.describe('Account')
console.log(`Label : ${meta.label}`);
console.log(`Num of Fields : ${meta.fields.length}`);
```

--------------------------------

### Get Recently Accessed Records for an SObject

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/history.html.md

Use `SObject.recent()` to retrieve a list of recently accessed records for a specific SObject. This is useful for quickly accessing frequently viewed records.

```javascript
/* @interactive */
const res = await conn.sobject('Account').recent()
console.log(res)
```

--------------------------------

### Multi-Record Create with AllOrNone Option

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20180726-jsforce19-features.html.md

Demonstrates how to perform a multi-record create operation in JSforce, with the `allOrNone` option set to true. This ensures that if any record fails to insert, the entire operation is rolled back and an error is thrown.

```javascript
const accounts = [
  { Name: 'ABC, Inc.' },
  { Name: 'DEF, Inc.' },
  ...
];
conn.sobject('Account')
  .create(accounts, { allOrNone: true })
  .then((rets) => {
    // All accounts are successfully inserted
    for (const ret of rets) {
      assert(ret.success === true);
    }
  })
  .catch((err) => {
    // some of the records failed in insertion
  });
```

--------------------------------

### Upload records using createJob, open, uploadData, and close

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/v2-bulk.html.md

This snippet demonstrates how to create a Bulk V2 job, open it, upload records (as an array or CSV stream), and then close the job for processing.

```APIDOC
## Upload records using createJob, open, uploadData, and close

### Description
This method allows you to insert records in bulk into Salesforce using the Bulk V2 API. It involves creating a job, opening it, uploading data, and then closing the job.

### Method
`conn.bulk2.createJob(options).open().uploadData(data).close()`

### Parameters
#### `createJob` options
- **operation** (string) - Required - The operation to perform (e.g., "insert").
- **object** (string) - Required - The Salesforce object to operate on (e.g., "Account").

#### `uploadData` parameters
- **data** (Array | string | Stream) - Required - The records to upload. Can be an array of objects, a CSV string, or a Node.js readable stream.

### Request Example
```javascript
const accounts = [
  { Name : 'Account #1' },
  { Name : 'Account #2' },
  { Name : 'Account #3' },
];

const job = conn.bulk2.createJob({
  operation: "insert",
  object: "Account",
});

// The `open` event will be emitted when the job is created.
job.on('open', (job) => {
  console.log(`Job ${job.id} succesfully created.`);
});

await job.open();
await job.uploadData(accounts);
await job.close();
```

### Response
#### Success Response
- **Job ID** - The ID of the created Bulk V2 job.
- **Job Status** - The status of the job after closing (e.g., 'UploadComplete').

#### Response Example
```javascript
// After job.close() is called, the job will start processing.
// You can poll for its status using job.poll().
// Example of job.poll() response (simplified):
// {
//   "id": "750xxxxxxxxxxxx",
//   "operation": "insert",
//   "object": "Account",
//   "createdById": "005xxxxxxxxxxxx",
//   "createdDate": "2023-01-01T10:00:00.000Z",
//   "lastModifiedDate": "2023-01-01T10:05:00.000Z",
//   "systemModstamp": "2023-01-01T10:05:00.000Z",
//   "status": "JobComplete",
//   "numberCanceled": 0,
//   "numberCompleted": 3,
//   "numberFailed": 0,
//   "numberRetrying": 0,
//   "numberTotal": 3,
//   "retriesRemaining": 10,
//   "contentType": "CSV",
//   "createdDate": "2023-01-01T10:00:00.000Z",
//   "elapsedTimeInSeconds": 300,
//   "jobType": "V2",
//   "lineEnding": "LF"
// }
```
```

--------------------------------

### Describe Specific Tooling Object

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/tooling.html.md

Get detailed information about a specific tooling object, such as `ApexPage`, by calling `conn.tooling.sobject('ApexPage').describe()`. This returns the object's label and the number of fields.

```javascript
const res = await conn.tooling.sobject('ApexPage').describe()
console.log(`Label : ${res.label}`);
console.log(`Num of Fields : ${res.fields.length}`);
```

--------------------------------

### Authorize JSforce REPL with OAuth2

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md

Use the `.authorize` command to initiate an OAuth2 flow for a more secure and persistent connection to Salesforce. This command will open a browser window for authentication.

```bash
> .authorize
```

--------------------------------

### Get Recently Updated Record IDs

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/history.html.md

Use `SObject.updated(startDate, endDate)` to retrieve the IDs of records that have been updated within a specified date range. This is helpful for synchronization or auditing purposes.

```javascript
/* @interactive */
const res = await conn.sobject('Account').updated('2014-02-01', '2014-02-15');
console.log(`Latest date covered: ${res.latestDateCovered}`);
console.log(`Updated records : ${res.ids.length}`);
```

--------------------------------

### Deployment Timeout and Status Check

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md

Demonstrates a scenario where a deployment times out, providing a process ID. The subsequent command shows how to check the status using this ID.

```bash
$ jsforce-deploy -c username@example.org -D ./pacakge
Logged in as: username@example.org
Deploying to server...
Polling time out. Process Id = 0Af28000009s9RYCAY
```

```bash
$ jsforce-deploy -c username@example.org --pid 0Af28000009s9RYCAY
Logged in as: username@example.org

Deploy Succeeded.

Id: 0Af28000009s9RYCAY
Status: Succeeded
Success: true
Done: true
Number Component Errors; 0
Number Components Deployed: 188
Number Components Total: 188
Number Test Errors; 0
Number Tests Completed: 0
Number Tests Total: 0
```

--------------------------------

### Get Recently Accessed Records Across All Objects

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/history.html.md

Use `Connection.recent()` to retrieve a list of recently accessed records across all SObject types. This provides a consolidated view of your recent activity.

```javascript
/* @interactive */
const res = await conn.recent()
console.log(res)
```

--------------------------------

### Making a POST Request with Helper Method

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/request.html.md

Use `Connection.requestPost()` for POST requests. It automatically serializes the body and sets `content-type` to `application/json`.

```javascript
/* @interactive */
const requestBody = {
  operation: 'query',
  query: 'SELECT Id, Name FROM Account LIMIT 1000',
};

const res = await conn.requestPost('/services/data/v47.0/jobs/query', requestBody);
console.log(res);
```

--------------------------------

### Visualforce Remote Objects Configuration

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20150405-querying-salesforce-without-consuming-api-quota.html.md

Configure Visualforce Remote Objects to define Apex objects and their fields for client-side access. This setup allows querying without direct API calls.

```html

        
            
        
    
```

--------------------------------

### Stream Input to Bulk Batch

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/bulk.html.md

Illustrates how to pipe an input stream to a writable stream provided by `Bulk-Batch.stream()` for processing.

```APIDOC
## Stream Input to Bulk Batch

### Description
This method allows you to pipe an input stream directly to a writable stream associated with a bulk batch, enabling efficient data processing.

### Method
`batch.stream()` and `inputStream.pipe(batch.stream())`

### Parameters
* `inputStream` (ReadableStream) - The stream containing the data to be processed.
* `batch.stream()` - Returns a Node.js standard writable stream that accepts batch input.

### Request Example
```javascript
const batch = await conn.bulk.load("Account", "insert");
batch.on("response", (rets) => { 
  for (const 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(', ')}`);
    }
  }
});
csvFileIn.pipe(batch.stream());
```
```

--------------------------------

### Create Apex Class using Tooling API

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/tooling.html.md

Use `conn.tooling.sobject('ApexClass').create()` to create new Apex classes. The `body` parameter accepts the Apex code as a string.

```javascript
const apexBody = [
  "public class TestApex {",
  "  public string sayHello() {",
  "    return 'Hello';",
  "  }",
  "}"
].join('\n');
const res = await conn.tooling.sobject('ApexClass').create({
  body: apexBody
});
console.log(res);
```

--------------------------------

### Query Custom Fields Using Previous Results

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20150826-how-to-use-jsforce-web-console.html.md

Combine SOQL with previous command results to fetch specific data, such as all custom fields for an Account object. This example utilizes ES6 arrow functions.

```javascript
query(
  `SELECT Id, Name, DataType
   FROM CustomField
   WHERE EntityDefinition.KeyPrefix = '${_2.keyPrefix}'`
)
```

--------------------------------

### Retrieve Metadata to Local Directory

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20151106-jsforce-metadata-tools.html.md

Fetches metadata from Salesforce and extracts it to a specified local directory. Ensure a package.xml file exists in the target directory.

```bash
$ jsforce-retrieve -c username@example.org -D ./pacakge
Logged in as: username@example.org
Retrieving from server...

Retrieve Succeeded.

Id: 09S28000001cnRfEAI
Status: Succeeded
Success: true
Done: true

Extracting:  package/pages/Page1.page
Extracting:  package/pages/Page1.page-meta.xml
Extracting:  package/pages/Page2.page
Extracting:  package/pages/Page2.page-meta.xml
Extracting:  package/classes/Class1.cls
Extracting:  package/classes/Class1.cls-meta.xml
Extracting:  package/classes/Class2.cls
Extracting:  package/classes/Class2.cls-meta.xml
Extracting:  package/package.xml
```

--------------------------------

### Generic Request Method

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/request.html.md

The `Connection.request()` method allows you to make arbitrary REST API calls. For GET requests, you can pass a string URL. For other HTTP methods, provide an object with method, URL, body, and headers.

```APIDOC
## GET Request

### Description
Make a GET request to a specified endpoint.

### Method
GET

### Endpoint
`/services/data/v47.0/ui-api/object-info`

### Request Example
```javascript
/* @interactive */
const res = await conn.request('/services/data/v47.0/ui-api/object-info');
console.log(res)
```

## POST Request with Body

### Description
Make a POST request with a JSON body to a specified endpoint.

### Method
POST

### Endpoint
`/services/data/v47.0/jobs/query`

### Request Body
- **operation** (string) - Required - The type of operation.
- **query** (string) - Required - The SOQL query.

### Request Example
```javascript
/* @interactive */
const requestBody = {
  operation: 'query',
  query: 'SELECT Id, Name FROM Account LIMIT 1000',
};

const res = await conn
  .request({
    method: 'POST',
    url: '/services/data/v47.0/jobs/query',
    body: JSON.stringify(requestBody),
    headers: {
      'content-type': 'application/json',
    },
  });
console.log(res)
```
```

--------------------------------

### Get Current User Identity

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/identity.html.md

Use `conn.identity()` to fetch the current API session user's identity information. This includes details like user ID, organization ID, username, and display name.

```javascript
/* @interactive */
const res = await conn.identity()
console.log(`user ID: ${res.user_id}`);
console.log(`organization ID: ${res.organization_id}`);
console.log(`username: ${res.username}`);
console.log(`display name: ${res.display_name}`);
```

--------------------------------

### Connect using an authorized username

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/documents/blog/posts/20140115-jsforce-repl-tips.html.md

After authorizing with OAuth2, you can use the `.connect` command with your username. JSforce will automatically refresh the access token if needed, eliminating the need to enter a password.

```bash
> .connect username@example.org
Refreshing access token ... 
Logged in as : username@example.org
>
```

--------------------------------

### Access Token Authentication

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/connection.html.md

Establishes a connection using a Salesforce access token and instance URL.

```APIDOC
## Access Token

### Description
Establishes a connection using a Salesforce access token and instance URL. This is typically obtained after a successful login or OAuth2 authorization.

### Method
`new jsforce.Connection(config)`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```javascript
const jsforce = require('jsforce');

const conn = new jsforce.Connection({
  instanceUrl : '',
  accessToken : ''
});
```

### Response
#### Success Response (200)
Connection object is initialized.

#### Response Example
None
```

--------------------------------

### Get Recently Deleted Record IDs

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/history.html.md

Use `SObject.deleted(startDate, endDate)` to retrieve the IDs of records that have been deleted within a specified date range. This method returns the earliest available date and the latest date covered by the query.

```javascript
/* @interactive */
const res = await conn.sobject('Account').deleted('2014-02-01', '2014-02-15');
console.log(`Ealiest date available: ${res.earliestDateAvailable}`);
console.log(`Latest date covered: ${res.latestDateCovered}`);
console.log(`Deleted records : ${res.deletedRecords.length}`);
```

--------------------------------

### Login and Query Salesforce Data

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/top/node-example.html.md

Connect to Salesforce, log in with credentials, and execute a SOQL query to retrieve Account records. Ensure you have the necessary username and password.

```javascript
const jsforce = require('jsforce');

const conn = new jsforce.Connection();
await conn.login('username@domain.com', 'password')

const res = await conn.query('SELECT Id, Name FROM Account')
console.log(res)
```

--------------------------------

### Search Users with Query Parameters - Chatter API

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/chatter.html.md

Retrieve a collection of users, filtering by a query parameter like 'q' for name. You can also specify offset and limit for pagination. Refer to the Chatter REST API Guide for all acceptable query parameters.

```javascript
/* @interactive */
const result = await conn.chatter.resource('/users', { q: 'Suzuki' }).retrieve();

console.log("current page URL: " + result.currentPageUrl);
console.log("next page URL: " + result.nextPageUrl);
console.log("users count: " + result.users.length);

for (let i=0; i .connect username@salesforce.example.org
Password: *******
Logged in as : username@salesforce.example.org
> query("SELECT Id, Name FROM Account LIMIT 1")
{ totalSize: 1,
  done: true,
  records: 
   [ { attributes: [Object],
       Id: '0015000000KBQ5GAAX',
       Name: 'GenePoint' } ] }
> .exit

```

--------------------------------

### Bulk Query with Record Stream

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/bulk.html.md

Demonstrates how to perform a bulk query and receive the results as a stream of individual records.

```APIDOC
## Bulk Query with Record Stream

### Description
This functionality allows you to execute a bulk query and process the results as a stream of individual records, suitable for real-time handling.

### Method
`conn.bulk2.query(SOQL_query)`

### Parameters
* `SOQL_query` (string) - The SOQL query to execute.

### Response
* `recordStream` (ReadableStream) - A stream emitting 'record' events for each retrieved record.

### Request Example
```javascript
const recordStream = await conn.bulk2.query('SELECT Id, Name, NumberOfEmployees FROM Account')

recordStream.on('record', (data) => {
  console.log(record.Id);
});

recordStream.on('error', (err) => {
  throw err;
});
```
```

--------------------------------

### Create and Open a Bulk V2 Job

Source: https://github.com/jsforce/jsforce.github.io/blob/main/src/partials/document/v2-bulk.html.md

Initiate a new Bulk V2 ingest job for a specified operation and object. The job is created and then opened to prepare for data upload. Listen for the 'open' event to confirm job creation.

```javascript
const job = conn.bulk2.createJob({
  operation: "insert",
  object: "Account",
})

// the `open` event will be emitted when the job is created.
job.on('open', (job) => {
  console.log(`Job ${job.id} succesfully created. `)
})

await job.open()
```