In this tutorial you are going to learn how to make use of Cloud Code in your Parse.com powered app. We will shed light on what Cloud Code Functions, Background Jobs and the various before* and after* hooks are.

Prequesites
To follow the tutorial you should have a Parse app setup and the Parse CLI should be installed as well. If you haven’t done that yet, please do this now by following the instructions to install the Parse Cloud Code CLI. Let us also create a test class for this tutorial and call it Person. We will add two columns to it as well, both of type String, name one of them firstName and the other one lastName. To have something to work with, we will also add two objects to the class, John and Jane Doe.

The sample class Person and two sample entries

What you will learn
At the end of this tutorial you will have a basic idea of how Cloud Code on Parse works, how to write a function and how ti run Cloud Code once an object gets saved.

What is Cloud Code?
The term Cloud Code refers to the JavaScript code that runs on the Parse servers to either react to changes to your data and to de-couple logic from the client code. This is valuable for apps that are available on multiple platforms as you don’t have to rewrite your logic in each native language and you can iterate very fast without publishing app updates.

For example, if you want to make sure that properties of an object that is stored in your database has a certain format, you could either add client-side validation, and rewrite this code for each native platform your app runs on, or you simply create a beforeSave function in Cloud Code and let the server handle this. The advantage is clear, you write validation code once and changing it to account for edge-cases you might have not thought of yet can be implemented fast and easy.

Writing your first Cloud Coude Function
First off, create a directory for your project, open a terminal window, cd into the directory of your project and type parse new CloudCodeTutorial. This will create all the directories and files you need for your project. Now that this is done, open the main.js file from the cloud directory. Ignore the other two directories for now.

The file already contains a sample function which should give you an idea of how to write a very simple function. We will now write a function that queries a specific Person object from our database and return the full name of the person.
A simple Cloud Code function

Back to business, lets get our hands dirty and write the function to return the full name of a person. Begin by adding the code for the function to your main.js file, save it and run parse deploy to upload the codeto Parse. If everything goes well, we should now be able to run this function.

Parse.Cloud.define("fullname", function(request, response) {
  // Get the personId parameter from the request
  var personId = request.params.personId;

  // Create a new query and fetch the object with the ID personId
  var query = new Parse.Query("Person");
  query.get(personId, {
    success: function(person) {
      response.success("Hello, "+person.get("firstName")+" "+person.get("lastName"));
    },
    error: function(error) {
      response.error(error.message);
    }
  });
});

Now that the code is deployed and ready to run, we want to give it a try. The below curl call will run the function and return the results. Simply replace YOUR_PARSE_APP_ID, YOUR_REST_API_KEY and OBJECT_ID with the values for your app, copy it into the terminal and run it.

curl -X POST \
  -H "X-Parse-Application-Id: YOUR_PARSE_APP_ID" \
  -H "X-Parse-REST-API-Key: YOUR_REST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"personId":"OBJECT_ID"}' \
  https://api.parse.com/1/functions/fullname

The result of this API call should look like this:

{"result":"Hello, John Doe"}

Now that this works great, we want to add some more people to our database. To make sure that we always save a first and lastname, we will now create a beforeSave function that Parse runs automatically for us before an object for the defined class is saved. This is the perfect place for us to add some validation. Go back to your main.js and add the following code to it, save the file and run parse deploy again.

Parse.Cloud.beforeSave("Person", function(request, response) {

  if (typeof request.object.get("firstName") == 'undefined' ||
      typeof request.object.get("lastName") == 'undefined')
  {
    // Either first or lastname was not provided, so we reject the save
    response.error("Please provide a first and a lastname");
  }
  else
  {
    // All godd, proceed with saving the object
    response.success();
  }

});

Before we proceed, lets have a look at the code we just wrote for our beforeSave function even though it is pretty basic. First, we check that the type of the two required parameters, firstName and lastName, is undefined, read, they have not been sent in the request. If this is the case we use the error() method of the response object to signal an error to Parse and with that we reject the save and return the error message to the client.

If everything is fine, and we received a value for firstName and lastName we will signal a success by calling response.success and the object will be saved to our database. Lets try this out with the follwoing API requests:

# Don't send a firstName and lastName, this should return an error
curl -X POST \
  -H "X-Parse-Application-Id: YOUR_PARSE_APP_ID" \
  -H "X-Parse-REST-API-Key: YOUR_REST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}' \
  https://api.parse.com/1/classes/Person

Now lets send a valid request by sending a value for firstName and lastName:

curl -X POST \
  -H "X-Parse-Application-Id: YOUR_PARSE_APP_ID" \
  -H "X-Parse-REST-API-Key: YOUR_REST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"firstName":"Maggy","lastName":"Doe"}' \
  https://api.parse.com/1/classes/Person

The second API call should create a new Person object with the first and lastname set correctly and return a response containing the objectId of the newly created object and the creation time

{"createdAt":"2015-03-03T21:44:24.638Z","objectId":"z4lUAf1nsO"}

Knowing the limits
When you decide wether or not you want to implement parts of the app in Cloud Code, you should know about the limits first. A function can run for up to 15 seconds of wall-clock time before the systems terminates it. The various before and after functions are limited to a total of 3 seconds. Also, if you have a function that runs for about 14 seconds, and a beforeSave is triggered from this function, the beforeSave actually only has 1 second to run. So choose wisely what you do.

Background Jobs are less restricted here, allowing for up to 15 minutes of runtime. They are always a good joice when you need to do more heavy data-processing and can also be scheduled to run. So if you are building a game and want to calculate the highest score of the day once per day, background jobs are the way to go.

Recap
You should now have a basic understanding on how to write a Cloud Code funtion, how to trigger it and how to perform actions whenever an object gets saved. There is many more you can do with Cloud Code, for example sending e-mails using the Mailgun Module or integrate with the Twilio API. You should definitely check all of this out in the official Cloud Code documentation and make your app better and easier to maintain.