Platform

Deploy and call your first Cloud Code functions

Introduction

Until here, you have learned how to create an app, install Parse SDK and create a simple CRUD in your application. Now you are able to implement more business rules and make your app unique using Cloud Code functions.

Cloud Code function is a tool that let you run a NodeJS function in Back4App Cloud. Back4App executes your code only when you call the function via API or via SDK. Using Cloud Code it’s also possible to create functions that are triggered by your app events.

The coolest thing about Cloud Code Functions is that when you update them, they become available to all mobile/web/IoT environments instantly and you don’t have to wait for a new release of your application. This makes it possible for you to change app behavior on the fly and add new features faster.

So, to help you use this powerful tool, we will teach you how to manage ParseObjects using Cloud Code Functions.

Prerequisites

To complete this tutorial, you will need:

Goal

  • To implement a Cloud Code Function to update objects on your application database at Back4App.

Step 1 - Create your cloud function code

First, you have to create a main.js file to put your code into. Then, you have to define a function using Parse.Cloud.define inside this file.

Cloud functions start on the main.js file. If you want to use other .js files, you can import them using the require('./nameFile.js') function at this main file.

Now, imagine that your application is related to soccer players and you have to store data about the players, as their names, years of birth, attributes, etc.

A notable attribute for players born in 2000, for example, is that they are young. So imagine that, after realizing this, you want to update all players born in 2000 attribute to “young” at Back4App database. To do this, you can use a Cloud Code Function.

First, you will need to query players whose year of birth is 2000. You can use the equalTo method inside your Cloud Code to do so. After that, you can update the attributes information of the players retrieved from Back4App database to “young”, using the code below.

It’s important to highlight that there are lots of other options to query ParseObjects. You can find out more about them in Parse Official Documentation.

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Parse.Cloud.define("updatePlayer", function(request, response) {
  const attributes = request.params.attributes;
  const yearOfBirth = request.params.yearOfBirth;
  const query = new Parse.Query("SoccerPlayers");
  query.equalTo('yearOfBirth', yearOfBirth);
  query.find()
  .then((results) => {
    // The object was retrieved successfully.

    for (let i = 0; i < results.length; i++) {
      var object = results[i];

      object.set("attributes", attributes);
      object.save();
    }

    response.success(results.length + " objects are saved!");
  }, (error) => {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
    response.error("Save failed! " + error);
  });
});

Step 2 - Upload function to Cloud Code

After creating your Cloud Code, you have to upload it to Back4App. To do so, go to Back4App website, log in, click on My Apps section, find your app. Then, you will be able to deploy Cloud Code Functions by following one of the options described below.

You can click on SERVER SETTINGS.

After that, find the “Cloud Code” block and click on SETTINGS. The “Could Code” block looks like this:

Or you can click on DASHBOARD. After that, click on Core > Cloud Code Functions.

Either way, you will end up in the page shown below. To deploy your Cloud Code, simply click on the + ADD button and select the main.js file you created at Step 1, then click on the DEPLOY button.

Step 3 - Run the Cloud Code Function

To run the Cloud Code Function, call the method below through your application. To do so, use the code that corresponds to the technology of your project.

The code below won’t work as expected if you haven’t installed Parse SDK correctly for the technology of your project. So, check the Connect to Back4App tutorial to certify that you have installed Parse SDK correctly to your application.

1
2
3
Parse.Cloud.run('updatePlayer', { attributes: 'young', yearOfBirth: 2000 }).then(function(ratings) {
  // result should be 'Update object successfully'
});
1
2
3
4
5
6
7
8
9
10
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("attributes", "young");
params.put("yearOfBirth", 2000);
ParseCloud.callFunctionInBackground("updatePlayer", params, new FunctionCallback<Float>() {
  void done(Float result, ParseException e) {
    if (e == null) {
      // Update object successfully
    }
  }
});
1
2
3
4
5
ParseCloudFunction cloudFunction;
cloudFunction.setFunctionName("updatePlayer");
cloudFunction.add("attributes", "young");
cloudFunction.add("yearOfBirth", 2000);
ParseResponse response = cloudFunction.send();
1
2
3
4
5
PFCloud.callFunctionInBackground("updatePlayer", withParameters: ["attributes": "young", "yearOfBirth": 2000]) {
  (response: AnyObject?, error: NSError?) -> Void in
  let result = response as? Float
  // Update object successfully
}
1
2
3
4
5
6
7
8
[PFCloud callFunctionInBackground:@"updatePlayer"
  withParameters:@{@"attributes": @"young", @"yearOfBirth": @2000}
    block:^(NSNumber *ratings, NSError *error) {
    if (!error) {
       // Update object successfully
    }
  }
];
1
2
3
4
5
6
7
8
IDictionary<string, object> params = new Dictionary<string, object>
{
  { "attributes": "young", "yearOfBirth": 2000 }
};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("updatePlayer", params).ContinueWith(t => {
  var result = t.Result;
   // Update object successfully
});
1
2
3
4
5
6
7
8
IDictionary<string, object> params = new Dictionary<string, object>
{
  { attributes": "young", "yearOfBirth": 2000 }
};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("updatePlayer", params).ContinueWith(t => {
  var result = t.Result;
  // Update object successfully
});
1
2
$result = ParseCloud::run("updatePlayer", array("newNameGroup" => "Group 8", "year" => 1998));
  // Update object successfully
curl -X POST \
  -H "X-Parse-Application-Id: APPLICATION_ID" \
  -H "X-Parse-REST-API-Key: REST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "attributes": "young", "yearOfBirth": 2000 }' \
  https://parseapi.back4app.io/functions/updatePlayer

Conclusion

At this point, you have learned how to use Cloud Code functions to update objects stored at Back4App database. In case you face any trouble while deploying your code, please contact our team via chat!