Develop Functions

This section explains the basic developer workflow when developing a new function. This section also details how to add build and run-time configurations for your functions.

When you’re done developing your function, deploy your function to a Salesforce compute environment and invoke your function from your org.

Create a Function Project 

To create a function, start by creating a Salesforce DX project.

The DX project name you choose represents the Salesforce Functions project name, which you use when invoking a deployed function. A Salesforce Functions project name must be unique to the org. The project name is listed in the sfdx-project.json configuration file.

Next, use the generate:function command to populate your project with the template source files and the metadata file for your function. For example, to create a JavaScript-based function named myfunction, use the following command from your DX project root directory:

1sf generate function -n myfunction -l javascript

The function name must be only lowercase letters or numbers, and must start with a lowercase letter.

The only supported languages for the -l/--language arguments are javascript, typescript, and java.

Note

Creating a function adds the <project root>/functions/<function name> directory to your DX project and creates default source files and build definition files for the function in that directory. Here’s an example DX project with function-specific files created for a JavaScript function named myfunction:

1├── functions
2│ └── myfunction
3│  ├── index.js
4│  └── project.toml
5│  └── package.json
6|  └── README.md
7|  └── test
8|    └── index.test.js

For a step-by-step guide to creating a Functions project, see Quick Start.

Configure Function Dependencies 

Each function must provide a list of dependencies that the function must have to build and run. Function dependency information is provided in language-specific configuration files.

Set JavaScript and TypeScript Dependencies 

JavaScript or TypeScript functions specify dependencies and build configuration information in a Node.js package.json file in the <project root>/functions/<function name>/ directory. This file is required to build and run your JavaScript or TypeScript function. For details on the format and fields for a Node.js package.json file, see https://nodejs.org/docs/latest/api/packages.html#nodejs-packagejson-field-definitions.

Using npm install with the Node.js package.json is recommended when you start developing a function, which installs dependencies to enable things like type support for TypeScript functions code in VS Code. You can also use npm build to verify you’ve added the right set of dependencies.

Generated JavaScript and TypeScript functions include the Salesforce Functions Runtime for Node.js in the package.json file:

1{
2  "name": "myfunction-function",
3  "dependencies": {
4    "@heroku/sf-fx-runtime-nodejs": "^0.14.0"
5  }
6}

Set Java Dependencies 

Dependencies are defined in your function’s pom.xml file for use with the Maven build tool. The following pom.xml file includes the Salesforce SDK for Java Functions in the list of dependencies:

1<?xml version="1.0" encoding="UTF-8"?>
2
3<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5  <modelVersion>4.0.0</modelVersion>
6
7  ...
8
9  <dependencies>
10    <dependency>
11      <groupId>com.salesforce.functions</groupId>
12      <artifactId>sf-fx-sdk-java</artifactId>
13      <version>0.5.0-ea</version>
14    </dependency>
15    ....
16  </dependencies>

For more information on Maven and pom.xml files, see https://maven.apache.org/.

Configure Function Information in project.toml 

Each function must provide a project.toml TOML file that contains function metadata. This file usually resides in your <project root>/functions/<function name> directory. The generate:function command creates a template project.toml file that looks something like this:

1[_]
2schema-version = "0.2"
3
4[com.salesforce]
5schema-version = "0.1"
6id = "myfunction"
7description = "My Function description"
8type = "function"
9salesforce-api-version = "56.0"

On creation, salesforce-api-version reflects the current version of the Salesforce REST API that the Functions SDK uses. Salesforce Functions supports API version 53.0 or later.

Note

Update this TOML file with any function metadata information you need. For a list of the valid fields for project.toml see Function Metadata TOML Files. For details on the general TOML file format, see toml.io.

Include the Appropriate Salesforce SDK 

In your function code, import the Salesforce Functions SDK for your programming language.

When you generate a function with sf generate function, these dependencies are included in the example code.

Note

Use JavaScript and TypeScript 

There’s no Salesforce Functions SDK required when writing Salesforce Functions code in JavaScript.

In TypeScript, include the Salesforce Functions SDK for Node.js with import:

1import { InvocationEvent, Context, Logger, RecordQueryResult } from "sf-fx-sdk-nodejs";

Use Java SDK Import 

In Java, import classes that you need from the com.salesforce.functions.jvm.sdk package, for example:

1import com.salesforce.functions.jvm.sdk.Context;
2import com.salesforce.functions.jvm.sdk.InvocationEvent;
3import com.salesforce.functions.jvm.sdk.SalesforceFunction;

Add the Function Entry Point 

Functions that access Salesforce data must have a specific code entry point that can be invoked with the invoking org’s context data and payload.

Specify JavaScript and TypeScript Entry Point 

In JavaScript and TypeScript, specify and export a execute entry point. The following JavaScript example provides an execute entry point function:

1export default async function execute(event, context, logger) {
2  // function code
3}

The following TypeScript example provides an execute entry point function:

1export default async function execute(
2  event: sdk.InvocationEvent,
3  context: sdk.Context,
4  logger: sdk.Logger,
5): Promise<any> {
6  // function code
7}

Specify Java Entry Point 

Java functions must provide a public class that implements the SalesforceFunction interface and overrides the public apply() method. The following example provides an implementation of apply() using FunctionInput and FunctionOutput classes defined elsewhere in the function project code:

1public class ExampleFunction implements SalesforceFunction<FunctionInput, FunctionOutput> {
2
3  @Override
4  public FunctionOutput apply(InvocationEvent<FunctionInput> event, Context context)
5      throws Exception {
6
7    // Function code
8    ...
9
10    return new FunctionOutput(myResultData);
11  }
12}

The types supported for the input and output for SalesforceFunction are specific to the Java SDK and are described in Java Functions.

Add Your Project to GitHub 

Salesforce Functions require that source code is tracked with git. When developing a function, add your project to a GitHub repo and push your function code changes regularly to collaborate with other developers. Functions code, unlike Apex code, doesn’t get deployed to your org, so you can’t use your orgs as a way to share code.

Function code must be committed to git before you can deploy a function. However, merging your function code to a github.com remote repo isn’t required, although generally a good practice.

Note

To add your project to GitHub, navigate to github.com in your browser. Log in to your github.com account, and create a repository. Save the git URL for your new repo. See Create a Repo for more details.

In the DX project root directory, use the following git commands:

1git init
2git add .
3git commit -m "Initial project commit after project creation"
4git remote add github <git URL for your github.com repo>

Access Salesforce Resources 

Connect to additional Salesforce resources using the Salesforce Functions SDK for your language (Node.js or Java). The Salesforce Functions SDKs provide an integrated programming model for writing business logic that connects with your data in the Salesforce Platform.

Use Context and DataApi 

The SDKs provide context data for the calling org when your function is invoked. The data is passed as a parameter to your function entry point. Through this context you can query and execute DML on your org data. Record access is controlled using the Functions permission set in your org.

Through the context data you can access the DataApi interface to query, insert, and update records.

The following JavaScript example uses context.org.dataApi to make a simple query to the org that invoked the function:

1export default async function execute(event, context, logger) {
2  const query = "SELECT Id, Name FROM Account";
3  const results = await context.org.dataApi.query(query);
4  logger.info(JSON.stringify(results));
5
6  return results;
7}

The following Java example uses the DataApi class from the context data to do a query:

1import com.salesforce.functions.jvm.sdk.data.Record;
2
3...
4
5List<Record> records =
6    context.getOrg().get().getDataApi().query("SELECT Id, Name FROM Account").getRecords();

Discover the UnitOfWork Class 

For more complex access, such as complex or large transactions, the Salesforce Functions SDKs provide the UnitOfWork class. A UnitOfWork represents a set of one or more Salesforce operations that must be done as a single atomic operation. Single atomic operations reduce the number of requests back to the org, and is more efficient when working with larger data volumes. UnitOfWork also lets you manage data operations in your own transactions.

The following JavaScript example (from the Context_UnitOfWork_JS sample) uses a UnitOfWork to create an Account record and related records:

1export default async function (event, context, logger) {
2  logger.info(`Invoking unitofworkjs Function with payload ${JSON.stringify(event.data || {})}`);
3
4  // Validate Input
5  const payload = event.data;
6  validateField("accountName", payload.accountName);
7  validateField("lastName", payload.lastName);
8  validateField("subject", payload.subject);
9
10  // Create a unit of work that inserts multiple objects.
11  const uow = context.org.dataApi.newUnitOfWork();
12
13  // Register a new Account for Creation
14  const accountId = uow.registerCreate({
15    type: "Account",
16    fields: {
17      Name: payload.accountName,
18    },
19  });
20
21  // Register a new Contact for Creation
22  const contactId = uow.registerCreate({
23    type: "Contact",
24    fields: {
25      FirstName: payload.firstName,
26      LastName: payload.lastName,
27      AccountId: accountId, // Get the ReferenceId from previous operation
28    },
29  });
30
31  // Register a new Case for Creation
32  const serviceCaseId = uow.registerCreate({
33    type: "Case",
34    fields: {
35      Subject: payload.subject,
36      Description: payload.description,
37      Origin: "Web",
38      Status: "New",
39      AccountId: accountId,
40      ContactId: contactId,
41    },
42  });
43
44  try {
45    // Commit the Unit of Work with all the previous registered operations
46    const response = await context.org.dataApi.commitUnitOfWork(uow);
47    // Construct the result by getting the Id from the successful inserts
48    const result = {
49      accountId: response.get(accountId).id,
50      contactId: response.get(contactId).id,
51      caseId: response.get(serviceCaseId).id,
52    };
53    return result;
54  } catch (err) {
55    const errorMessage = `Failed to insert record. Root Cause : ${err.message}`;
56    logger.error(errorMessage);
57    throw new Error(errorMessage);
58  }
59}

When using the Node.js SDK only, always use a new instance of UnitOfWork for each transaction and never reuse a committed UnitOfWork.

Note

The following Java example (from the Context_UnitOfWork_Java sample) uses the UnitOfWork class from the Salesforce SDK for Java Functions (with Input and Output defined elsewhere in the function code):

1@Override
2public FunctionOutput apply(InvocationEvent<FunctionInput> event, Context context)
3    throws Exception {
4
5  String accountName = event.getData().getAccountName();
6  String firstName = event.getData().getFirstName();
7  String lastName = event.getData().getLastName();
8  String subject = event.getData().getSubject();
9  String description = event.getData().getDescription();
10
11  DataApi dataApi = context.getOrg().get().getDataApi();
12
13  // Create a Unit of Work that inserts multiple objects
14  UnitOfWorkBuilder unitOfWork = dataApi.newUnitOfWorkBuilder();
15
16  // You can use the DataApi to create a Record
17  Record account = dataApi.newRecordBuilder("Account").withField("Name", accountName).build();
18  // A ReferenceId will be returned to assign relationships with other objects within the same
19  // transaction
20  ReferenceId accountRefId = unitOfWork.registerCreate(account);
21
22  Record contact =
23      dataApi
24          .newRecordBuilder("Contact")
25          .withField("FirstName", firstName)
26          .withField("LastName", lastName)
27          .build();
28  ReferenceId contactRefId = unitOfWork.registerCreate(contact);
29
30  // Here we are using the accountRefId and contactRefId to specify the relationship with the
31  // temporary Id's created by the Unit of Work builder
32  Record serviceCase =
33      dataApi
34          .newRecordBuilder("Case")
35          .withField("Subject", subject)
36          .withField("Description", description)
37          .withField("Origin", "Web")
38          .withField("Status", "New")
39          .withField("AccountId", accountRefId)
40          .withField("ContactId", contactRefId)
41          .build();
42  ReferenceId serviceCaseRefId = unitOfWork.registerCreate(serviceCase);
43
44  // The transaction will be commited and all the three objects are going to be created. The
45  // resulting map contains the Id's of the created objects
46  Map<ReferenceId, RecordModificationResult> result =
47      dataApi.commitUnitOfWork(unitOfWork.build());
48
49  LOGGER.info("Function successfully commited UoW with {} affected records!", result.size());
50
51  // Construct the result by getting de Id's from the created objects
52  return new FunctionOutput(
53      result.get(accountRefId).getId(),
54      result.get(contactRefId).getId(),
55      result.get(serviceCaseRefId).getId());
56}

UnitOfWork uses the Composite Graph API for efficient transaction requests with higher record limits. For more details on the Composite Graph API see: REST API Developer Guide: Composite Graphs. Note the Composite Graph API limits, such as a maximum of 15 different nodes or objects or both in one payload, also apply to UnitOfWork.

Use Salesforce APIs 

If the provided SDK classes don’t give you the data access you need, you can try making REST API calls directly to the calling org.

In the Salesforce SDK for Node.js Functions, you can use context.org.dataApi.accessToken to obtain the API access token for the invoking org. This token can be used with your preferred HTTP request framework to make REST API calls back to the invoking org. You can also use the token to initialize a JSForce connection to access these APIs:

1import jsforce from "jsforce";
2
3jsforceConn = new jsforce.Connection({
4  accessToken: context.org.dataApi.accessToken,
5  instanceUrl: context.org.domainUrl,
6  version: context.org.apiVersion,
7});

In the Salesforce SDK for Java Functions, you can use DataApi.getAccessToken() to obtain the API access token for the invoking org. Use your API access token with your preferred HTTP request framework to make REST API calls back to the invoking org.

Be Aware of API Limits 

Most org access from functions is similar to an API request to an org through something like the Salesforce REST API, and has similar limits. See Limits.

Use Functions Buildpacks and Runtime Environment 

The commands run:function:start and project:deploy use a specific set of buildpacks to build the container image for your function.

Deployed functions currently run in the Heroku-22 environment.

Learn how you can Use Heroku Data in Functions.

Tip

Product Retirement Announcement

Salesforce Functions is no longer available for purchase or renewal. To preserve the capabilities that Salesforce Functions provided to your org, deploy an alternative solution before your existing order term ends. See Salesforce Functions Retirement for more information on migrating your functions. Contact your Salesforce Account Executive for more information on Heroku.