Offload Compute Intensive or Security Sensitive Functions to the Server.
Define Cloud Functions
Follow the tutorial for an introduction to Cloud Functions: Tutorial
For complex apps, sometimes you need a bit of logic that isn’t running on a mobile device. Cloud Code makes this possible.
Cloud Code is easy to use because it’s built on the same Moralis JavaScript SDK that powers thousands of apps. The only difference is that this code runs in your Moralis Dapp rather than running on the user’s mobile device. When you update your Cloud Code, it becomes available to all mobile environments instantly. You don’t have to wait for a new release of your application. This lets you change app behaviour on the fly and add new features faster.
Even if you’re only familiar with mobile development, we hope you’ll find Cloud Code straightforward and easy to use.
Note: Starting June 2022 you can only write Cloud Function code through CLI/IDE (setup).
Let’s look at a slightly more complex example where Cloud Code is useful. One reason to do the computation in the cloud is so that you don’t have to send a huge list of objects down to a device if you only want a little bit of information.
For example, let’s say you’re writing an app that lets people review movies. A single Review object could look like this:
{"movie": "The Matrix","stars": 5,"comment": "Too bad they never made any sequels."}
If you wanted to find the average number of stars for The Matrix, you could query for all of the reviews, and the average amount of stars on the device. However, this uses a lot of bandwidth when you only need a single number. With Cloud Code, we can just pass up the name of the movie, and return the average star rating.
Cloud Functions accept a JSON parameters dictionary on the request object, so we can use that to pass up the movie name. The entire Moralis JavaScript SDK is available in the cloud environment, so we can use that to query over Review objects. Together, the code to implement averageStars looks like this:
cloud.js
Moralis.Cloud.define("averageStars",async (request) => {constquery=newMoralis.Query("Review");query.equalTo("movie",request.params.movie);constresults=awaitquery.find();let sum =0;for (let i =0; i <results.length; ++i) { sum += results[i].get("stars"); }return sum /results.length;});
The only difference between using averageStars and hello is that we have to provide the parameter that will be accessed in request.params.movie when we call the Cloud Function. Read on to learn more about how Cloud Functions can be called.
Global Packages
The following packages are available globally within Cloud Function code and can be used without a require statement.
Cloud Functions cannot have state. They can read and write data to the database but you can't create global variables like in the example below.
cloud.js
let name ="Satoshi"; // NOT ALLOWEDMoralis.Cloud.define("functionName",async (request) => {let age =20; // allowed});
The reason is that your cloud code will get load balanced across many instances of your server so that Moralis can infinitely scale your app.
Note: The different instances of your server won't share any variables defined outside the function bodies.
All instances of your server will share the same database. Therefore if you need to share data across instances it's recommended you store it in the database.
What happens if I create global variables?
You will get unexpected results. Consider the example below.
cloud.js
let count =0; // very badMoralis.Cloud.define("increment",async (request) => {logger.info(count); count++;});// If you call the function above you may get the following results// 0// 0// 0// 1// 1// 2// 1// 3// 0// 2
Why is the increment function not working properly?
Because each time the request gets randomly routed to different instances of your server and each instance has its own separate count variable.
Therefore we hope you now understand why you should not use global variables 🙌
What about global constants?
Global constants are ok to use as they will just be copied to all instances and won't change.
IDE Setup
You can find instructions specifically for your server in the server's settings in the Cloud Functions tab
You can write your Cloud Functions in your preferred IDE by making use of the moralis-admin-cli.
To get started, you need to install it by running the following code in the terminal:
npminstall-gmoralis-admin-cli
After you have installed the Moralis Admin CLI, you can head to the admin panel and open up the Cloud Functions on the server you want to work on.
In the lower part of the modal, there will be a code snippet that you need to run in the terminal.
The only thing you need to change is the path to the local JavaScript folder on your computer that contains the Cloud Functions.
After you've run the command, the cloud code will be updated automatically on the backend with each save!
Legacy UI is present in the video, some things might be different
Debugging
For debugging or informational purposes it's often useful to print messages. A logger can be obtained for this purpose. It will print messages to the Moralis Dashboard in the "Logs > Info" section.
In general, two arguments will be passed into Cloud Functions:
request - The request object contains information about the request. The following fields are set:
params - The parameters object is sent to the function by the client.
user - The Moralis.User that is making the request. This will not be set if there was no logged-in user.
If the function is successful, the response in the client looks like this:
{ "result": 4.8 }
If there is an error, the response in the client looks like this:
{"code": 141,"error": "movie lookup failed"}
Call via REST API
Cloud Functions can be called directly using a simple GET request. Add your Moralis App Id and any Cloud Function arguments as query parameters to your Moralis server URL. Say you had the following Cloud Function:
cloud.js
Moralis.Cloud.define("Hello", (request) => {return`Hello ${request.params.name}! Cloud functions are cool!`;});
Then the URL would look something like the following:
It’s important to make sure the parameters required for a Cloud Function are provided and are in the necessary format. you can specify a validator function or object which will be called prior to your Cloud Function.
Let’s take a look at the averageStars example. If you wanted to make sure that request.params.movie is provided, and that averageStars can only be called by logged-in users, you could add a validator object to the function.
cloud.js
Moralis.Cloud.define("averageStars",async (request) => {constquery=newMoralis.Query("Review");query.equalTo("movie",request.params.movie);constresults=awaitquery.find();let sum =0;for (let i =0; i <results.length; ++i) { sum += results[i].get("stars"); }return sum /results.length; }, { fields: ["movie"], requireUser:true, });
If the rules specified in the validator object aren’t met, the Cloud Function won’t run. This means that you can confidently build your function, knowing that request.params.movie is defined, as well as request.user.
Advanced Cloud Function Validation
Often, not only is it important that request.params.movie is defined, but also that it's the correct data type. You can do this by providing an Object to the fields parameter in the "Validator."
cloud.js
Moralis.Cloud.define("averageStars",async (request) => {constquery=newMoralis.Query("Review");query.equalTo("movie",request.params.movie);constresults=awaitquery.find();let sum =0;for (let i =0; i <results.length; ++i) { sum += results[i].get("stars"); }return sum /results.length; }, { fields: { movie: { required:true, type: String,options: (val) => {returnval.length<20; }, error:"Movie must be less than 20 characters", }, }, requireUserKeys: { accType: { options:"reviewer", error:"Only reviewers can get average stars", }, }, });
This function will only run if:
request.params.movie is defined.
request.params.movie is a String.
request.params.movie is less than 20 characters.
request.user is defined.
request.user.get('accType') is defined.
request.user.get('accType') is equal to ‘reviewer.’
The full range of built-in validation options are:
requireMaster: Whether the function requires a masterKey to run.
requireUser: Whether the function requires a request.user to run.
validateMasterKey: Whether the validator should run on masterKey (defaults to false).
fields: An Array or Object of fields that are required on the request.
requireUserKeys: An Array of fields to be validated on request.user.
The full range of built-in validation options on .fields are:
type: The type of the request.params[field] or request.object.get(field).
default: What the field should default to if it’s null.
required: Whether the field is required.
options: A singular option, an array of options, or a custom function of allowed values for the field.
constant: Whether the field is immutable.
error: A custom error message if validation fails.
You can also pass a function to the Validator. This can help you apply reoccurring logic to your Cloud Code.
cloud.js
constvalidationRules= (request) => {if (request.master) {return; }if (!request.user ||request.user.id !=="masterUser") {throw"Unauthorized"; }};Moralis.Cloud.define("adminFunction", (request) => {// do admin code here, confident that request.user.id is masterUser, or masterKey is provided }, validationRules);Moralis.Cloud.define("adminFunctionTwo", (request) => {// do admin code here, confident that request.user.id is masterUser, or masterKey is provided }, validationRules);
SOME CONSIDERATIONS TO BE AWARE OF
The validation function will run prior to your Cloud Code Functions. You can use async and promises here, but try to keep the validation as simple and fast as possible so your cloud requests resolve quickly.
As previously mentioned, cloud validator objects will not validate if a master key is provided, unless validateMasterKey:true is set. However, if you set your validator to a function, the function will always run.
Units
Moralis units are available inside your cloud functions.
In order to successfully run the units function you always need to specify a method and a value.
For more details on the Web3.js contract interface, see the web3.eth.Contract section of the Web3.js docs.
Contract ABI
To find the ABI for a contract already published on Ethereum's Mainnet you can look on Etherscan by searching for the contract address and looking in the "Contract" tab. There are similar block explorers for other chains where the ABI is published. For instance, you can go to BscScan for Binance Smart Chain.
For your own contracts, the ABI can be found in the build directory after compiling the contract