*

CC Tutorial1 – Your First Script

In this tutorial we’ll go through the basics of creating a Cloud Code script, and teach you how to pass parameters to/from a script.

Step 1 – Create the Script

To create our first script, perform the following steps:

  • Log into the brainCloud Design Portal (if you haven’t already)
  • Choose you app, and go to Design | Cloud Code | Scripts
  • Click the [+] in the top right-hand corner to create a new script
  • Give your script a name – for example “Tut1_AddTwoNumbers”, make it Client Callable, and set its Test Parameters to:
{
  "num1": 1,
  "num2": 2
}
  • Then switch to the Editor tab, and copy and paste the following script.
Script   
  1. // Retrieve our two paramaters
  2. var a = data.num1;
  3. var b = data.num2;
  4.  
  5. // Perform our highly advanced calculation! 🙂
  6. var c = a + b;
  7.  
  8. // "Return" the result
  9. c;
  • Hit [Save] and then [Close] when you’re done.

Step 2 – Run the Script

Okay, lets see if it works. To run the script:

  • Switch to the API Explorer by choosing Design | Cloud Code | API Explorer from the side menu
  • The API Explorer attempts to simulate a client application accessing the brainCloud servers. Thus, just like any brainCloud client, you must first authenticate.  To do so, choose the Authenticate Service and the Authenticate Operation from the drop-downs, and then click the green RUN button.
  • Next, we’ll run the script. Choose Script from the Service drop-down and Run Script “Tut1_AddTwoNumbers” from the Operation drop-down. If you don’t see your script you probably forgot to make it Client Callable – go to its definition in the Scripts screen, and then come back.
  • You’ll notice that the default parameters that you set are displayed in the Parameters section of the API Explorer. Edit them if you wish. Then click the RUN button to run the script and see the results.

CloudCodeTutorial1

 


Step 3 – View the results

The following results are returned from running the script:

  • status = the HTTP result of the operation, which will always be 200, unless there were problems with the server
  • data = the results from the script itself – which will contain two parts:
    • success = will be true unless an exception was triggered
    • response = the exact results returned from the script
Results   
{
 "status": 200,
 "data": {
  "response": 3,
  "success": true
 }
}

Step 4 – Calling the Script from your client app

Calling scripts from client apps is straight-forward – you simply call the RunScript() method, passing in the name of the script, and any required parameters.

Calling the script from a Unity C# app would look like the following:

// Call the script
results = BrainCloudWrapper.GetBC().BrainCloudScript.RunScript(
  "Tut1_AddTwoNumbers",
  "{ \"num1\": 1, \"num2\": 2 }",
  OnSuccess_AddScript,
  OnError_AddSript,
  null );