Hi everyone ! Today let’s present briefly the new generally available feature that came with Winter 22’and that will certainly please those of you that are more comfortable with Java or Javascript languages: Salesforce Function ! ❄️❄️❄️
First, Salesforce Functions allow you to create server-side logic in other languages than pure Apex ! But also to communicate with your database easily thanks to a set of tools. The code is run separately from your org (but still inside the Salesforce platform) and the authentication is taken care of automatically, so it’s always that less to worry about.
To be able to use it, you will need a specific license, and then you can activate it directly in the setup.
Create and develop a function on Salesforce Function
You can create a Salesforce function with the command: sf generate function -n myfunction -l language
. This generates a file in you project, outside of the force-app folder. For now, the available languages are: javascript, typescript and java.
Furthermore, to be called by and org, a function must have three parameters: event
, context
and logger
. The event contains the data (such as parameters) that you pass from Apex to your function. The context represents your Salesforce org and allows you to run queries and perform DML operations on the database using the Data API. Logger represents (surprise) the Salesforce logger, so it’ll allow you to keep track of what’s happening in the function with a set of methods like debug
, or error
.
How communication with an org works
Secondly, to call a function from an Apex class, you first need to create an object that will serve as a link to the function in Apex. This is done using the functions.Function.get('MyProject.myfunction')
method.
After initiating the communication with the function, you can call it synchronously using the method invoke(payload)
(the payload will be in the event parameter that we saw earlier) or asynchronously by adding a callback function: invoke(payload, callback)
.
Now, once the function starts running, it can access your org database using the context parameter mentioned before. For instance you can run context.org.dataApi.query(soql)
to retrieve some records, or context.org.dataApi.update(account)
to update one.
Summary and references
In conclusion, Salesforce Functions is a powerful feature ! It allows you to report some of your Apex logic outside your org. This allows us to run computationally expensive calculations. Besides it makes available all the libraries widely used is Java and Javascript for a variety of use cases !
Here are some references if you need to go further. As this article only showed a glimpse of what functions can do :)
- The post in the release notes
- The documentation
- How to try functions locally
- An overview of the feature
If you haven’t read Meryam’s article yet, here is the link !