Get Started

Deploy and call your first Cloud Code functions

Introduction

After using the Back4App’s data store capabilities, it’s time to learn how to use Cloud Code Functions.

Cloud code allows your application to automatically run javascript-based functions on the server-side(Back4App) in response to events triggered by Parse and HTTP requests. Your JavaScript code is stored in the Back4App servers and runs in a managed environment. As a result, there’s no need to manage and scale your own servers. Database triggers, request validators, and integrations are common use cases for Cloud Code, but you can do whatever your application needs, including using any npm module in your functions.

Prerequisites

To complete this tutorial, you will need:

Goal

  • To deploy and execute a cloud function from your App

Step 1 - Create a main.js file

The first and mandatory step is to create a main.js file. This file will be deployed on the cloud folder(./cloud/main.js) inside your Back4App project.

Cloud Code Functions must be declared inside your main.js file. If you want to declare functions in other files, you should import the files on the main.js using the require('./nameFile.js')

Step 2 - Create your first Cloud Code Function

Let’s now create some functions inside your main.js file. Below you can find some cloud functions examples.

main.js

1
2
3
4
5
6
7
8
9
10
//This is a hello function and will log a message on the console
Parse.Cloud.define("hello", async (request) => {
    console.log("Hello from Cloud Code!");
    return "Hello from Cloud Code!";
});

//Note that Cloud functions accept a JSON parameters dictionary on the request object.
Parse.Cloud.define("sumNumbers", async (request) => {
    return (request.params.number1 + request.params.number2);
});

Cloud functions accept a JSON parameters dictionary on the request object, so we can use that to pass up the numbers on the example above. The entire Parse JavaScript SDK is available in the cloud environment, so we can use that to query over Review objects.

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
24
25
//Now you will create a new data object, a ToDo item, definning the title and the status. 
Parse.Cloud.define("createToDo", async (request) => {
    const title = request.params.title;
    const done = request.params.done;

    const todo = new Parse.Object('ToDo');

    todo.set('title', title);
    todo.set('done', true);

    try {
        return await todo.save();
      } catch (error) {
        console.log('ToDo create - Error - ' + error.code + ' ' + error.message);
        return error
      }
});

// Here you will query the ToDo class 
Parse.Cloud.define("getListToDo", async (request) => {
    let query = new Parse.Query("ToDo");
    query.equalTo("done",true);
    query.descending("title");
    return await query.find();
});

Step 3 - Upload function to Cloud Code

After creating your Cloud Code, you have to upload and deploy it on Back4App. Go to your App Dashboard and click over Cloud Code.

Click on the ADD button and then select your main.js file to upload it.

Then click over DEPLOY to deploy the files on Back4App servers.

After conclude the deploy process you will see a success message. Click over your main.js to visualize it on the Dashboard Cloud Code preview. Note that the main.js icon color changed from green to blue.

Step 4 - 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
4
5
6
7
8
9
10
11
12
13
const helloFunction = await Parse.Cloud.run("hello");


const params1 = {number1:3, number2:4}
const sum = await Parse.Cloud.run('sumNumbers', params1);


const params2 = {title:"Launch my App", done:true}
const createToDo = await Parse.Cloud.run('createToDo', params2);


const getToDos = await Parse.Cloud.run('getListToDo');

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    //The hello function Executes a cloud function with no parameters that returns a Map object
    final ParseCloudFunction function = ParseCloudFunction('hello');
    final ParseResponse parseResponse = await function.execute();
    if (parseResponse.success && parseResponse.result != null) {
      print(parseResponse.result);
    }
   
   //the sum function Executes a cloud function with parameters that returns a Map object
    final ParseCloudFunction function = ParseCloudFunction('sumNumbers');
    final Map<String, dynamic> params = <String, dynamic>{
      'number1': 10,
      'number2': 20
    };
    final ParseResponse parseResponse =
        await function.execute(parameters: params);
    if (parseResponse.success) {
      print(parseResponse.result);
    }

     //the createToDo function executes a cloud function that returns a ParseObject type
    final ParseCloudFunction function = ParseCloudFunction('createToDo');
    final Map<String, dynamic> params = <String, dynamic>{
      'title': 'Task 1',
      'done': false
    };
    final ParseResponse parseResponse =
        await function.executeObjectFunction<ParseObject>(parameters: params);
    if (parseResponse.success && parseResponse.result != null) {
      if (parseResponse.result['result'] is ParseObject) {
        //Transforms the return into a ParseObject
        final ParseObject parseObject = parseResponse.result['result'];
        print(parseObject.objectId);
      }
    }

      //the getListToDo function executes a cloud function with parameters that returns a Map object    
    final ParseCloudFunction function = ParseCloudFunction('getListToDo');
    final ParseResponse parseResponse = await function.execute();
    if (parseResponse.success) {
      if (parseResponse.result != null) {
        for (final todo in parseResponse.result) {
          //Use fromJson method to convert map in ParseObject 
          print(ParseObject('ToDo').fromJson(todo));
        }
      }
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//calling the hello function
ParseCloud.callFunctionInBackground("hello", new HashMap(), (FunctionCallback<String>) (string, e) -> {
            if (e == null) {
                Log.d("result", string);
            }else{
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
});

//calling the sum function
HashMap<String, Integer> params = new HashMap();
params.put("number1", 1);
params.put("number2", 2);
ParseCloud.callFunctionInBackground("sumNumbers", params, (FunctionCallback<Integer>) (number, e) -> {
            if (e == null) {
                Log.d("result", number+"");
            }else{
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
});

//calling the createToDo function
HashMap<String, Object> params = new HashMap();
params.put("title", "Hello World!");
params.put("done", true);
ParseCloud.callFunctionInBackground("createToDo", params, (FunctionCallback<ParseObject>) (obj, e) -> {
    if (e == null) {
        Log.d("result", obj.get("title")+"");
    }else{
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

//calling the getToDoList function
ParseCloud.callFunctionInBackground("getListToDo", new HashMap(), (FunctionCallback<List<ParseObject>>) (list, e) -> {
            if (e == null) {
                for (ParseObject obj:list) {
                    Log.d("result", obj.get("done")+"");
                }
            }else{
              Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
struct Todo: ParseObject {
  //: Those are required for Object
  var objectId: String?
  var createdAt: Date?
  var updatedAt: Date?
  var ACL: ParseACL?
  //: Your own properties.
  var title: String = ""
  var done: Bool = false
  //: Custom initializer.
  init(title: String, done: Bool) {
    self.title = title
    self.done = done
  }
  init(objectId: String?) {
    self.objectId = objectId
  }
}
struct CloudString: ParseCloud {
  //: Return type of your Cloud Function
  typealias ReturnType = String
  //: These are required for Object
  var functionJobName: String
}
struct CloudNumber: ParseCloud {
  //: Return type of your Cloud Function
  typealias ReturnType = Float
  //: These are required for Object
  var functionJobName: String
  //: If your cloud function takes arguments, they can be passed by creating properties:
  var number1: Int
  var number2: Int
}
struct CloudTodo: ParseCloud {
  //: Return type of your Cloud Function
  typealias ReturnType = Todo
  //: These are required for Object
  var functionJobName: String
  //: If your cloud function takes arguments, they can be passed by creating properties:
  var title: String = ""
  var done: Bool = false
}
struct CloudListTodo: ParseCloud {
  //: Return type of your Cloud Function
  typealias ReturnType = [Todo]
  //: These are required for Object
  var functionJobName: String
}

let cloudString = CloudString(functionJobName: "hello")
    cloudString.runFunction { result in
      switch result {
      case .success(let response):
        print("Response from cloud function hello: \(response)")
      case .failure(let error):
        assertionFailure("Error calling cloud function hello: \(error)")
      }
    }
     
    let cloudNumber = CloudNumber(functionJobName: "sumNumbers", number1: 10, number2: 20)
    cloudNumber.runFunction { result in
      switch result {
      case .success(let response):
        print("Response from cloud function sumNumbers: \(response)")
      case .failure(let error):
        assertionFailure("Error calling cloud function sumNumbers: \(error)")
      }
    }
     
    let cloudTodo = CloudTodo(functionJobName: "createToDo", title: "My Test Todo", done: false)
     
    cloudTodo.runFunction { result in
      switch result {
      case .success(let response):
        print("Response from cloud function createToDo: \(response)")
      case .failure(let error):
        assertionFailure("Error calling cloud function createToDo: \(error)")
      }
    }
     
    let cloudListTodo = CloudListTodo(functionJobName: "getListToDo")
     
    cloudListTodo.runFunction { result in
      switch result {
      case .success(let response):
        print("Response from cloud function createToDo: \(response)")
      case .failure(let error):
        assertionFailure("Error calling cloud function createToDo: \(error)")
      }
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
IDictionary<string, object> params = new Dictionary<string, object>
{};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("hello").ContinueWith(t => {
  var result = t.Result;
});


IDictionary<string, object> params = new Dictionary<string, object>
{
  { "number1": 10, "number2": 9}
};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("sumNumbers", params).ContinueWith(t => {
  var result = t.Result;
});


IDictionary<string, object> params = new Dictionary<string, object>
{						
  { "title": "cook", "done": true}						
};						
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("createToDo", params).ContinueWith(t => {						
  var result = t.Result;						
});


IDictionary<string, object> params = new Dictionary<string, object>						
{};						
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("getListToDo").ContinueWith(t => {						
  var result = t.Result;						
});						

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
IDictionary<string, object> params = new Dictionary<string, object>
{};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("hello").ContinueWith(t => {
  var result = t.Result;
});


IDictionary<string, object> params = new Dictionary<string, object>
{
  { "number1": 10, "number2": 9}
};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("sumNumbers", params).ContinueWith(t => {
  var result = t.Result;
});


IDictionary<string, object> params = new Dictionary<string, object>
{						
  { "title": "cook", "done": true}						
};						
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("createToDo", params).ContinueWith(t => {						
  var result = t.Result;						
});


IDictionary<string, object> params = new Dictionary<string, object>						
{};						
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("getListToDo").ContinueWith(t => {						
  var result = t.Result;						
});						
1
2
3
4
5
6
7
8
9
10
11
$result = ParseCloud::run("hello");


$result = ParseCloud::run("sumNumbers", array("number1" => 7, "number2" => 20));


$result = ParseCloud::run("createToDo", array("title" => "cook", "done" => false));				
echo 'Task created with success!';	


$result = ParseCloud::run("getListToDo");

curl --location --request POST 'https://parseapi.back4app.com/functions/hello' \
--header 'X-Parse-Application-Id: ApplicationID' \
--header 'X-Parse-REST-API-Key: REST-API-KEY' \
--data-raw ''

curl --location --request POST 'https://parseapi.back4app.com/functions/sumNumbers' \
--header 'X-Parse-Application-Id: ApplicationID' \
--header 'X-Parse-REST-API-Key: REST-API-KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
    "number1":1,
    "number2":1
}'

curl --location --request POST 'https://parseapi.back4app.com/functions/createToDo' \
--header 'X-Parse-Application-Id: ApplicationID' \
--header 'X-Parse-REST-API-Key: REST-API-KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
    "title":"Hello Sir!",
    "done":true
}'

curl --location --request POST 'https://parseapi.back4app.com/functions/getListToDo' \
--header 'X-Parse-Application-Id: ApplicationID' \
--header 'X-Parse-REST-API-Key: REST-API-KEY' \
--data-raw ''

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!