Introduction to Salesforce Functions

Introduction to Salesforce Functions
In this blog, you will get to know about Salesforce Functions, when to use, how it works and what you need to create and deploy a Salesforce Function.

Introduction to Salesforce Functions

Introduction

  • You can use Salesforce Functions to build and integrate individual blocks of logic which extend your apps using the languages and tools of your choice. 

  • You write code that performs a specific task on trusted, managed Salesforce infrastructure, pre authenticated and preconfigured to use Salesforce data. 

  • Apex code, or a low-code solution such as a Salesforce Flow, then invokes your code on demand.

  • Your function automatically scales to meet the load. Since Salesforce Functions is built and managed by Salesforce, this frees your app design from the API limits encountered by off-platform solutions.

  • Your function is automatically authenticated to the org invoking the function at run-time, meaning that you don’t have to worry about dealing with authentication or other external system access complexity.

With Salesforce Functions, perform compute-heavy tasks that were previously challenging to do in your org. Salesforce elastically scales compute resources for your functions. This means you don’t manually have to modify compute resource configurations whenever you update a function. The functions are written with open languages and tools, and run on our platform with preconfigured secure access to Customer 360 data.


When to Use

  • Complex business calculations, such as loan processing, managing product license keys, contract billing, and demand forecasting.

  • Batch processing, such as daily inventory stocking, consumer goods assortments, ERP calculations, and material resource planning.

  • Resource-intensive back-office automation, such as document generation, mail merges, invoice creation, payroll processing, QR codes, and case routing.

  • Pick and choose which compute tasks you want to manage with Salesforce Functions. Quickly deliver computation-heavy workloads by invoking a function using Apex or a low-code solution.

  • Once you see how effective your first function is, you’ll likely want to create more. And if you keep your programming centralized, it’s easier to maintain and deploy changes as part of your own continuous integration and continuous deployment (CI/CD) environment.

How Salesforce Functions Work?

A function is your code, run on-demand, in Salesforce Functions elastic compute environments. Once you add functions to your Salesforce projects for your complex business logic code, Salesforce Functions takes care of everything else necessary to invoke your code in a secure and self-scaling environment.

The Functions developer workflow typically involves the following steps.

  • Develop your function, using the programming language of your choice (such as JavaScript, Java, or TypeScript).
    • Use your favorite development environment on your local workstation. Salesforce suggest VS Code, and Salesforce provides VS Code extensions to help you along.
    • A functions project in VS Code displaying invocation responses from the server Or you can use what you like with the Salesforce CLI. Once you’re ready to test, you can run your function locally and validate using scratch or sandbox orgs.


  • Deploy your function to the Salesforce Functions infrastructure.
    • Use Salesforce Functions compute environments to manage your function’s application lifecycle.
    • Integrate Salesforce Functions as part of your SFDX projects into your CI/CD system as needed.

  • Invoke your deployed Function in your sandbox or production orgs.
    • Use Apex to securely offload heavy compute tasks to your functions without worrying about Salesforce org limits. 
    • Through Apex, you can include function invocation in your Salesforce application workflow via Flow, Lightning Web Components, or many other Salesforce features that can be extended with Apex to invoke your function.

What You Need to Create and Deploy a Salesforce Function?

Here’s the basic process for creating and deploying a function.

  • A Salesforce Functions license is required to enable functions for your DevHub org. Contact your Salesforce account representative for steps to acquire the license.

  • Set up a Developer Hub (DevHub) to create and manage scratch orgs. The scratch org is a source-driven and disposable deployment of Salesforce code and metadata, made for developers and automation.

  • Develop Functions locally. You can use the Salesforce CLI in conjunction with a text editor or IDE of your choice or VS Code and the extensions we provide.

  • Run, test, and debug locally while connected to a scratch org or sandbox.

  • Deploy function(s) using the command line.

  • When ready, You invoke it from an Apex class within an org.

How to Get Started with Salesforce Function using JavaScript

Open your VS Code and create a project, CTRL+Shift+P on windows machine, select SFDX: Create Project with Manifest.

Authorize a Salesforce Org by SFDX: Authorize an Org then create a Scratch Org SFDX: Create a Default Scratch Org.

Next use the SFDX: Create Function palette command to create a Function in the current DX project open in VS Code. 

If you create a JavaScript Function, this command installs package.json dependencies for the created Function.

Check index.js file under your function, this will look something like this. 


module.exports = async function (event, context, logger) {
       logger.info(`Invoking Functions with payload ${JSON.stringify(event.data || {})}`);
       const results = await context.org.dataApi.query('SELECT Id, Name FROM Account');
       logger.info(JSON.stringify(results));

       return results;
}


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

The SDKs provide context data for the calling org when your Function is invoked. This 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

Next use the SFDX: Start Function palette command to start a Function.

Now either you run your function through Terminals, or you can create a payload.json file under your function. This file can be empty, or you can use this to pass your parameter to the function. 

Click on Invoke(payload.json) on the top to execute the function. The result will show you all the accounts in your scratch org in the Output. 

You can modify your index.js file to create Account by passing account name from payload.json. 


 module.exports = async function (event, context, logger) {
    logger.info(`Invoking Functions with payload ${JSON.stringify(event.data || {})}`);
    const accountName=event.data.accountName;
    const results = await context.org.dataApi.create({
        type:'Account',
        fields:{
            Name:accountName
        }
    });
    
    logger.info(JSON.stringify(results));
    return results;
}


Before you execute account creation, make sure you use SFDX: Stop Function palette command to stop this Function. Then, use the SFDX: Start Function palette command to start this Function again. 

Click on invoke(payload.json) then you can check your output, you will find Account id, check your default org you can find an Account with name “SFDC SAGA” using this id. 


Resources:

Follow Us

Posted By : Sudeer Kamat Date :

view_module Related

  • Meet RecordAction: The Unsung Hero of Salesforce's Actions & RecommendationsMeet RecordAction: The Unsung Hero of Salesforce's Actions & Recommendations
  • Query All Files Permission To Retrieve ContentDocumentLink Object In #SalesforceWinter24ReleaseQuery All Files Permission To Retrieve ContentDocumentLink Object In #SalesforceWinter24Release
  • Contact Intelligence View In #SalesforceWinter24ReleaseContact Intelligence View In #SalesforceWinter24Release
  • Get Started with Customer Onboarding Faster In Financial Services Cloud In #SalesforceWinter24ReleaseGet Started with Customer Onboarding Faster In Financial Services Cloud In #SalesforceWinter24Release
  • Scan Your Solution with Ease Using Salesforce Code Analyzer Visual Studio Code Extension (Beta) In #SalesforceWinter24ReleaseScan Your Solution with Ease Using Salesforce Code Analyzer Visual Studio Code Extension (Beta) In #SalesforceWinter24Release

label Labels

Comments 0