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.
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:
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:
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:
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"34[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:
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 code3}
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 code7}
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>{23 @Override4 public FunctionOutput apply(InvocationEvent<FunctionInput>event, Context context)5 throws Exception{67 // Function code8 ...910 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 init2git 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));56 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;23...45List<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 ||{})}`);34 // Validate Input5 const payload = event.data;6 validateField("accountName", payload.accountName);7 validateField("lastName", payload.lastName);8 validateField("subject", payload.subject);910 // Create a unit of work that inserts multiple objects.11 const uow = context.org.dataApi.newUnitOfWork();1213 // Register a new Account for Creation14 const accountId = uow.registerCreate({15 type: "Account",16 fields:{17 Name: payload.accountName,18},19});2021 // Register a new Contact for Creation22 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 operation28},29});3031 // Register a new Case for Creation32 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});4344 try{45 // Commit the Unit of Work with all the previous registered operations46 const response = await context.org.dataApi.commitUnitOfWork(uow);47 // Construct the result by getting the Id from the successful inserts48 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@Override2public FunctionOutput apply(InvocationEvent<FunctionInput> event, Context context)3 throws Exception {45 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();1011 DataApi dataApi = context.getOrg().get().getDataApi();1213 // Create a Unit of Work that inserts multiple objects14 UnitOfWorkBuilder unitOfWork = dataApi.newUnitOfWorkBuilder();1516 // You can use the DataApi to create a Record17 Record account = dataApi.newRecordBuilder("Account").withField("Name", accountName).build();18 // A ReferenceId will be returned to assign relationships with other objects within the same19 // transaction20 ReferenceId accountRefId = unitOfWork.registerCreate(account);2122 Record contact =23 dataApi24 .newRecordBuilder("Contact")25 .withField("FirstName", firstName)26 .withField("LastName", lastName)27 .build();28 ReferenceId contactRefId = unitOfWork.registerCreate(contact);2930 // Here we are using the accountRefId and contactRefId to specify the relationship with the31 // temporary Id's created by the Unit of Work builder32 Record serviceCase =33 dataApi34 .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);4344 // The transaction will be commited and all the three objects are going to be created. The45 // resulting map contains the Id's of the created objects46 Map<ReferenceId, RecordModificationResult>result =47 dataApi.commitUnitOfWork(unitOfWork.build());4849 LOGGER.info("Function successfully commited UoW with {} affected records!", result.size());5051 // Construct the result by getting de Id's from the created objects52 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";23jsforceConn = 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.
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.