Server Code

Separate client code from server code

Here you’ll learn

How to create and run any kind of server side script.

The different kinds of server scripts, and the solutions they provide.

Manage the Debugger: a tool by Gamedonia to debug your scripts locally.

Sometimes applications become complex and you use some logic that can't run on a mobile device or has to be modified regularly. It is helpful to have some code on the server, that can be updated or modified at will without the need to deploy a new game verison. Server Code is what you need to build this logic easily.

When writing server code, you will use an API which is mostly equivalent to the used in the SDK, but you will work with the Javascript language. This Javascript is executed on Gamedonia servers in a sandboxed environment that secures its execution and tracks its performance. Server Code can be written directly from the Gamedonia Dashboard, either using our integrated editor, or writing externally and uploading it as a .js file. You can also use our Debugger, which can let you manage your scripts locally and test them before using them in a real enviroment.

Gamedonia calls will only work under a valid Gamedonia session. This means there needs to be a user logged in with Gamedonia. The main exceptions are, for obvious reasons, creating and logging users in.

Basics

As we mentioned previously, Gamedonia Server Code is written in Javascript so let's start by getting in touch with a straightforward example.

Simple script

Go to Gamedonia Dashboard and click on Server Code > Custom Scripts on the navigation menu.

You'll see the following popup where you can upload an external file as a custom script or directly create a new one by setting a name and clicking the Create Script button. For this sample we will set hello as the script's name.

The embedded script editor will be shown:

Write the following code at the editor:

	var res = {};
	res.message = "Hello world!!";
	response.success(res);

Save the script by clicking on the floppy disk icon. The script will be stored and available to execute. You can run it using the Gamedonia SDK:

GamedoniaScripts.Run("hello", new Dictionary<string,object>(), OnHello);
GamedoniaSDKScript::run("hello", CCDictionary::create(), this, gamedoniaResponseData_selector(MyClass::onHello));
[[Gamedonia script] run:@"hello" parameters:[NSDictionary alloc] callback:onHello];
GamedoniaScripts.run("hello", {}, onHello);
Gamedonia.Script.run("hello", , OnHello)

The response you will get for this script is the following:

{
    "message": "Hello world!!"
}

That's about it! Play with the script, modify the message, add new data to the return object and check the results. We will go over some more examples below.

Input/output parameters

All the server code scripts in Gamedonia have access to environment variables that can be accessed at any moment inside the script:

  • request: The request variable contains the following information:
    • params: A Javascript object that represents the input parameters of your script sent by the client.
    • user:. The user that is making the request to the script.
      • profile:. The profile of the user making the request.
  • response:. This object contains two main functions:
    • success:This function can take an optional parameter to send data back to the client app. You'll be calling this function to notify the client that the script execution was successful.
    • error:Calling this function stops the script execution flow and notifies the client app with an error.

We will puth this into practice with a more complex example. Let's imagine a library with books that can be reviewed by users and that can be rated with a score range of 1 to 10. We would model a simple BookReview entity like this:

{
    "name":"Star Wars I",
    "author":"George Lucas",
    "rating":9
}

The goal is to build a script to help us calculate the average rating for a single book. Obviously, you could perform a full search on the bookreviews collection on the game client and calculate the average value inside the client app. Although this solution is not bad, it’s not going to scale well with a huge amount of information. The way to avoid the overhead of querying over all the information is to perform the calculation on the server. Here it goes:

Our example script to calculate the average rating will look like this:

var query = "{\"name\":\"" + request.params.book + "\"}";
 
gamedonia.data.search("bookreviews", query, {
    success: function(results) {
            var sum = 0;
            for (var i = 0; i < results.size(); i++) {
                sum += results[i].rating;
            }
             
            var ret = new Object();
            ret.averageRating = sum / results.size();
            response.success(ret);
    },
    error: function(error) {
            response.error(error.message);
    }
});

You can invoke this script by setting this on your game client:

Dictionary<string,object> parameters = new Dictionary<string, object>(){{"book", "Star Wars I"}};
GamedoniaScripts.Run("averagerating", parameters, delegate (bool success, object data) {
	if (success) {
		//TODO: data contains the return values of the script
	} else {
		//TODO: the script throwed an error
	}
});
void MyClass::getAverage(CCString* book_title) {
    CCDictionary* parameters = CCDictionary::create();
    parameters->setObject(book_title->getCString(), "book");

    GamedoniaSDKScript::run("hello", parameters, this, gamedoniaResponseData_selector(MyClass::onAverageRating));
}

void MyClass::onAverageRating(bool success, CCDictionary* data) {
    if (success) {
        //TODO: data contains the return values of the script
    } else {
        //TODO: the script throwed an error
    }
}
NSDictionary * parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"Star Wars I",@"book",nil];
    
[[Gamedonia script] run:@"averagerating" parameters:parameters callback:^(BOOL success, NSDictionary *data) {
    if (success) {
        //TODO: data contains the return values of the script
    } else {
        //TODO: the script throwed an error
    }
}];
var parameters:Object = new Object();
parameters.book = "Star Wars I";

GamedoniaScripts.run("averagerating", parameters, function (success:Boolean, data:Object):void {
    if (success) {
        //TODO: data contains the return values of the script
    } else {
        //TODO: the script throwed an error
    }
});
local OnAverageRating = function (succes, data)
    if success then
        -- TODO: data contains the return values of the script
    else
        -- TODO: the script throwed an error
    end
end

local parameters = {}
parameters.book = Star Wars I"
Gamedonia.Scripts.run("averagerating", parameters, OnAverageRating)

The response you'll get is:

{
    "averageRating":7.5
}

Custom Scripts

Custom Scripts is a feature that allows your app to extend Gamedonia API by providing your own custom logic at the server side. By simply creating a script you'll be able to call it directly from the client side letting you create your custom endpoints inside the Gamedonia Backend.

The most common uses of Custom Scripts are:

  • Transform the standard response of an API call to Gamedonia in a different response structure.
  • Group some intensive data search processes in a single call. This improves your game’s performance a lot, because calling the Gamedonia API from the client multiple times would result in slower processes.

You can think of Custom Scripts as the solution to close the gap between what you want and what the standard Gamedonia API offers.

Group data example

In the following example you can see how a single list of matches is built by querying Gamedonia database twice. This is an example from a real game. In this case, the developers wanted to build a single list with all open matches, plus exactly 15 finished matches. Let's see how they solved it using a Custom Script.

	var responseData = new Array();
	var open = "{\"state\":\"open\"}";
	var finished = "{\"state\":\"finished\"}";
	var limit_finished = 15;

	getMatches();

	function getMatches() {
	    //Recover the list of open matches
	    gamedonia.data.search("matches", open, {
	        success: function(entities) { 
	            getFinishedMatches(entities);
	        }, 
	        error: function(error) {
	            response.error(error.message);
	        }
	    });
	}

	function getFinishedMatches(matches) {
	    //Recover the list of completed matches
	    gamedonia.data.search("matches", finished, limit_finished, "{d:-1}", {
	        success: function(entities) { 
	            matches.addAll(entities)
	            response.success(matches);
	        }, 
	        error: function(error) {
	            response.error(error.message);
	        }
	    });
	}

The script starts by building two different search criterias for the same matches collection. One search for the open matches and one for the finished matches. A search limit of 15 is defined in a variable, which will be used later in the script. Next, the function getMatches() is called inside the script.

As you can see all the magic happens in that function. getMatches() starts with a search query over the matches collection. Nested to that call, as you can see in its callback, a new function called getFinishedMatches is invoked. The getFinishedMatches function does a new search over the matches and merges the results in a single array.

The last step is putting the merged matches collection inside the response object of the script, and you’re done! Now, when you call this script you will get your custom results for the matches collection as a response.

How to run a Custom Script

It's a very easy process. You can run a Custom Script with two simple lines of code.

			Dictionary<string,object> parameters = new Dictionary<string, object>(){{"finished_matches",15}};
			GamedoniaScripts.Run("getmatches", parameters, delegate (bool success, object data) {
			    if (success) {
			        //TODO: data contains the return values of the script
			    } else {
			        //TODO: the script throwed an error
			    }
			});
		
			void MyClass::getMatches(int finished_matches) {
			    CCDictionary* parameters = CCDictionary::create();
			    parameters->setObject(finished_matches, "finished_matches");

			    GamedoniaSDKScript::run("getmatches", &parameters, this, gamedoniaResponseData_selector(MyClass::onGetMatches));
			}

			void MyClass::onGetMatches(bool success, CCDictionary* data) {
			    if (success) {
			        //TODO: data contains the return values of the script
			    } else {
			        //TODO: the script throwed an error
			    }
			}
		
			NSDictionary * parameters = [NSDictionary dictionaryWithObjectsAndKeys:15,@"finished_matches",nil];
			    
			[[Gamedonia script] run:@"getmatches" parameters:parameters callback:^(BOOL success, NSDictionary *data) {
			    if (success) {
			        //TODO: data contains the return values of the script
			    } else {
			        //TODO: the script throwed an error
			    }
			}];
		
			var parameters:Object = new Object();
			parameters.finished_matches = 15;

			GamedoniaScripts.run("getmatches", parameters, function (success:Boolean, data:Object):void {
			    if (success) {
			        //TODO: data contains the return values of the script
			    } else {
			        //TODO: the script throwed an error
			    }
			});
		
			local OnGetMatches = function (success, data)
			    if (success)
			        -- TODO: data contains the return values of the script
			    else 
			        -- TODO: the script throwed an error
			    end
			end

			local parameters = {}
			parametres.finished_matches = 15
			Gamedonia.Scripts.Run("getmatches", parameters, OnGetMatches)
		

In the first line, we build the parameters we want to send to the Custom Script, then we call the script by using the GamedoniaScripts.Run function. This function takes 3 parameters:

  1. Script name. This has to match exactly our custom script file name.
  2. Input parameters. The parameters that our script needs.
  3. Callback. The callback function that will be invoked as a response to the script call.

Server Hooks

A Server Hook is Gamedonia’s capability to add custom logic to events that are already happening in the Gamedonia API. Server Hooks are scripts attached to your game collections that will trigger under some circumstances. You can create and manage them at the Gamedonia Dashboard Server Code section. For each collection of your game you can setup 2 scripts:

  • Pre Save. Trigger that runs before an entity is created or updated.
  • Post Save. Trigger that runs after you create or update an entity.

The execution scheme that follows a Gamedonia API request generated by your game is the following:

Keep in mind that a Pre Save Server Hook is executed before Gamedonia API’s response is generated so it has impact on the execution time. On the other hand, a Post Save Server Hook is executed after Gamedonia API’s response is generated so it has no impact on the execution time.

Pre Save

As we mentioned previously, a Pre Save Server Hook is a trigger that runs before an entity is created or updated. Common use cases for this kind of script are:

  • Data validation. Use this hook to check that all the expected data of an entity is filled correctly and, if something is missing, rejects the request preventing your application from saving data that is not correct.
  • Compute entity extra fields. When you need to compute some extra fields using the ones incoming with the received entity, it prevents your app from storing incomplete or flawed information.

Data validation example

In the next code snippet we are checking if an entity of type "match" has the field name empty:

var match = request.object;

if (!match.name) {
    response.error("Missing field name");
}

Let's review the source code:

  1. First we obtain the received entity.
  2. We check if the name field is present on the match.
  3. If the check fails, we generate a response error that stops the request before saving the data to the data storage.

On the client side you'll get as result to the Api Call a false value in the success callback field.

Compute extra entity fields

In the next sample we are going to generate a new field called full_name inside the entity, using the name and last_name of the received entity:

	var personaldata = request.object;
	var full_name = personaldata.name + " " + personaldata.last_name;
	personaldata.full_name = full_name;

As you can see we are concatenating 2 fields to get a new one with the full information. We are directly modifying the request entity received, Gamedonia will save it automatically without having to do any extra calls to the API.

Post Save

Excuse us, we're processing the information.

Managing Server Hooks

You can manage anything related to the Server Hooks directly from the Dashboard at Server Code > Server Hooks. By clicking on that section you get to the server hooks management screen where you can manage scripts for each collection.

The previous table shows all attached scripts to any collection and the list of actions you can perform on them. Let's review in detail all the available options by looking closely at the configurations collection row.

  1. Add new script. Opens a popup that allows you to create a new script attached to the related event on the collection.
  2. Edit script. Opens the embedded Javascript code editor with the contents of the script, and allows you to edit it directly from the browser and save the changes.
  3. Download script. Allows you to download a script source code.
  4. Delete script. Removes a script from the specified collection event.

Remember that you can only add one script to each event of a collection. Also remember that the Users collection is always present and you don't need to create it explicitly.

Scheduled jobs

Scheduled jobs are scripts that will be executed periodically for a given schedule. They are created and configured at the Gamedonia Dashboard and are executed automatically following the schedule or at the developer's will at any moment.

An example of scheduled job would be a script that needs to be executed once a day or repeated a certain amount of times. Maybe you want to set a field of some user profiles to a certain value once a day?

To configure a Scheduled Job you need to set:

  • The period between executions ( minutes, hours, days... ).
  • If the execution should be run indefinitely or end after a certain amount of repetitions.
  • The amount of repetitions, if needed.
  • More details. For instance, if your repetition period is set in days, you will be able to set the hour of the day when the script will be executed (for instance: every 3 days at 23:00). The input hour refers to local time at the developer's web browser. It will be translated to Server time automatically.

Once the job is created, you have some options at your disposal:

  • Edit the job code by clicking on Edit script.
  • Change the schedule setup of the script by clicking on Edit Schedule.
  • Run the scheduled job at any moment by clicking on Run now.
  • You can also toggle the Enable/Disable option to activate the script or stop executing it for a while.

Script log

Gamedonia allows you to add log messages inside the scripts to debug it's execution. The log object is present in all the scripts and has 3 functions available to reflect the severity of the message ( log.info, log.warn, log.error). All messages are stored, you can check them on the Dashboard in the Server Code > Log section.

Here you can see a screenshot of the log browser:

Debugger

Gamedonia Server Code Debugger

It is the first version of a plugin for the open architecture of the Eclipse platform. We think that working in a familiar tool will help you develop more comfortably. For now, it will cover the backend functionalities of your game.

You'll be able to polish the Server Code you've scripted in Gamedonia Dashboard.

This plugin lets you develop and debug code locally, so no web browser failures will add to your development time. You can import and edit any script you previously created on Gamedonia Backend. They can be either Server Hooks or Custom Scripts, which you can download one by one, or all at once.

Besides, this plugin lets you create and edit projects with a Gamedonia structure, just as you would do in the Dashboard via web browser.

When you're done smashing bugs and you've got code you're happy with, simply upload the scripts back to the Gamedonia Dashboard to get them running into your game.

Debugger features

  • It is an Eclipse plugin — an IDE you're familiar with
  • Import Custom Scripts or Server Hooks from the Gamedonia Dashboard — one by one, or all at once
  • Develop locally all your scripts — create and edit Gamedonia Projects
  • Debug locally all your scripts — web browser failures won't waste your time
  • Upload Scripts back to the Gamedonia Dashboard — you’re done smashing bugs

Gamedonia Debugging Cycle

gamedonia-debugging-cycle

Installation

Download Eclipse IDE for Java Developers (Luna SR2 version) from here.

Older versions of Eclipse are not supported!

Open Eclipse and go to Help > Install new software...

The plugin is located at http://download.gamedonia.com. You will need to create an update site to retrieve the plugin.

Click on Add... and enter a name of your choice for the site, for example Gamedonia Debugger Site. Fill the location field with the URL: http://download.gamedonia.com.

Choose Gamedonia Tools > Gamedonia Debugger Feature and check the box. Then click on Install and Next.

Accept the terms of the license agreement. After that, you will be asked to accept a certificate, tick the checkbox and click Ok.

After the download finishes, Eclipse will ask you to restart. Do so.

Configuration

Now that you have installed the plugin, you need to open a new project and get the scripts from the Gamedonia server. If you didn't create any custom script or server hook yet, you can do that at the Gamedonia Dashboard, in the Server code section. Once you have custom scripts or server hooks uploaded to Gamedonia, you can start configuring your Debugger project:

Go to File > New Project… Choose Gamedonia > Gamedonia Project and click on Next.

Fill the settings with the API normal key, API master key and Secret from your game on Gamedonia and click on Test. You can get this information from the Information tab in the Gamedonia Dashboard. If you haven't created a game yet, check the Get Started section of our documentation.

If everything goes well, you will get a message saying: tested OK for game: [name_of_your_game].

IMPORTANT: You will also see a Debugger Url. Set this url as API Server Url instead of http://api.gamedonia.com in your code or project.

If you haven't initialized the Gamedonia SDK yet, check the Get Started guide of your platform of choice here.

Remember to set the Api Server Url back to http://api.gamedonia.com once you are done with debugging.

Then click on Next, give a name to your project and click on Finish.

You will be asked to open the Javascript perspective. Click on Yes.

The project contains the scripts you uploaded to the Gamedonia Dashboard. Now you are ready to use the Debugger.

Usage

To debug the server code scripts you just downloaded to your Eclipse plugin, you first need to start the debugger, set some breakpoints and then get the scripts to run on the server side. Let's do that step by step.

Starting the debugger

Right click on the project folder > Debug as... > Gamedonia Application.

The Debug Perspective will open and the debugger will be up and running. Now you are be able to debug your scripts normally (put breakpoints, watch variables, etc.).

To make the debugging task easier, you may want to have your scripts at hand from the Debug Perspective. To do that go to Window > Show View > Other...

Then search for package , select Java > Package Explorer and click OK.

Now you can access your scripts directly from the Debug Perspective.

Debugging your scripts

Once the debugger is running, we need the server scripts to be run from your game or directly at the Debugger.

IMPORTANT: Remember to set the API Server Url of your code or project to the one you see when right clicking in the project folder > Properties > Gamedonia Settings > Debugger Url instead of http://api.gamedonia.com. That way your project will point to the debugger and will be able to stop on breakpoints, etc. If the debugger is not running and the API Server Url is set to the Debugger Url, you will get an error.

Let's see some of the things you can do to debug your scripts:

  • Set breakpoints to stop the code flow.
  • Add expressions and watch variables.
  • Print logs to console.

Now let's debug an example server script:

In this example, the script handles a push message from the server. Let's set a couple of breakpoints, where the code execution will stop and we will be able to see the values of certain variables or expressions at that point in runtime.

To set a breakpoint, double click at the left of a code line. A rounded mark will appear, indicating that the code flow will pause there.

Now that we have set a couple breakpoints, let's add an expression, so that we can see its value at different points in the code flow.

To do that, just copy-paste the name of an expression (in this example, notification.notif_type ) to the Expressions tab.

Now we just need to execute the script on the server side. In this example, we request a push notification using the Unity3D Simple Push Sample. Take a look at this sample to be able to set up a small game with push notifications.

When we generate the push notification, the script we are debugging ( sendpush.js) will be called and the debugger will stop the execution at the first breakpoint.

Now you can see that the value of our expression is undefined, because the assign operation comes later in the code.

You can also check the Variables tab and see the value of the variables in the scope.

If you click on Run > Resume, the code execution will continue until the next breakpoint.

In this second breakpoint we set, you can see that the value of the expression added before has changed to sample-attribute , which is the value we gave it a couple lines above.

Now let's put a log output to console that will make it easier understand the code flow. In this example we print the sentence "The notification is ready!!" to console.

To do that, we need to call log.info("The notification is ready!!");

Once the code flow goes past that call, we will see our message printed in the Console window view.

Update files

Updating the files from Gamedonia lets you retrieve the scripts uploaded to Gamedonia. Don't worry about your local files, you will not lose them in the process. The Debugger renames them if it detects any differences in files with the same name.

To update a project folder:

Right click on the project folder and click on Gamedonia > Pull project from Gamedonia.

This will download the newest server version of the scripts. If there are any differences, the local copies will be renamed to oldScriptName.js[Year][Month][Day][Hour][Minute] of the last update. Remember that the server files will have priority even if the latest changes were done on the local files!

This can also be done with individual files by right-clicking on a single file and clicking on Gamedonia > Pull file from Gamedonia.

If a script is deleted on the Dashboard, this change won't be reflected on your Eclipse project even when updating the project. One easy way to keep your project up to date is to remove all files locally and pull the whole project again from Gamedonia.

Let's try to modify and update a file on a test project and see what happens. For this example we created and configured a test project with 2 custom scripts (myfirstscript.js and sendpush.js).

Now if you modify a script (for instance, if you change the alert message of the push message that the sendpush.js script handles) you will have 2 different versions, the local one with this modification and the online one on the Gamedonia Dashboard.

Now if you update the sendpush.js file (right click on the file > Gamedonia > Pull file from Gamedonia) the server version will be downloaded and will substitute the local one. So now your sendpush.js will have the same alert message as before, and the original local file will be renamed to sendpush.js[Year][Month][Day][Hour][Minute] of the last modification so that you don't lose the changes you made locally.

In the following screenshot you can see that the local file has been renamed and the one downloaded from Gamedonia is called sendpush.js. Notice how Eclipse's code formatting isn't active, because after the rename the file name no longer ends with .js.

Remember that you need to manually upload your server code files (custom scripts or server hooks) to the Gamedonia Dashboard Server Code section once you are sure that you want to apply the changes you made.

Settings

Right click on the project folder, click on Properties and select Gamedonia Settings.

Here we can modify the API Url and the Debugger port. You can also check your Debugger Url and obtain it again by clicking on the Test button.

Uninstall

If you want to delete the Gamedonia Eclipse plugin, go to Help > Installation Details and select GamedoniaDebuggerFeature. Click on Uninstall and then Finish.

Eclipse will ask you to restart after uninstalling. Do so.

The script files you downloaded and the Eclipse project will remain. You can delete them manually in Eclipse.

Bulk Operations

Gamedonia Backend includes a specific API designed to be used from server side scripting that allows the developer to work with the MongoDB bulk operations support. Bulk operatinos are specially useful when you want to execute a large number of operations on a single collection and still keep the access to the API efficient and clean.

The Bulk API allows the construction of lists of operations that are executed in an optimal way by the database engine. All bulk operations are executed for a single collection.

There are 3 different types of operations that can be provided to the bulk API:

  • Insert
  • Update
  • Delete

The access to the bulk operations is done through the Data API exposed through server code. These functions should be used if we need to create a large number of documents in the database. Let's start by creating an insert bulk operation.

Insert

Building a bulk operation always has 2 steps:

  • Build the list of operations.
  • Execute the bulk operation for the specified operations list.

In the following block of code we are going to generate a bulk operation to create 1.000 database entries (for instance, cars in a racing game).

	var operations = []; // Javascript array where we are going to push the insert operations

	// Step 1 -  Create all the insert operations
	for (var k=0; k<1000; k++) {
		
		var car = new Object();
		car["car_number"] = k;
		car["car_type"] = "racer";

		var opp = gamedonia.data.createInsert(car); //Creates a new Insert operation
		operations.push(opp); // Adds the newly created operation to the array
	}			

	// Step 2 -  Run the operations stored in the array
	if (operations.length > 0) { // Checks whether the operations array is empty
	    log.info("Run bulk operations for cars (" + operations.length + ")");
	    
	    // Invokes bulk operation in the collection "cars" 
		gamedonia.data.runBulkOperations("cars", operations, { 		

			success: function(result) {  // Success handle for bulk operation
				log.info(“Created documents: ” + result.insertedCount);
	    	},
	    	error: function(error) { // Error handle for bulk operation
	    		log.error("Unable to run bulkoperation");
	    	}
	 	});   		    
	}	

The key lines for creating an insert bulk operation are the creation of each bulk operation:

	var opp = gamedonia.data.createInsert(entity);

And the execution of the whole group of operations with this line:

	gamedonia.data.runBulkOperations(collection_name, operations_list, callback);

Update

Creating an update operation is very similar. The main difference is that now you have to provide a search criteria that will be the one to locate the documents to be updated by the bulk operation. Let's see a complete block code:

	var operations_players = [];
	var query_update = "{\”rank\”:1, \”status\”:\”active\”}"; // This determines which entities will be updated
	var update = "{\”applyBonus\”: true}"; // This determines which fields will be changed and the values that this fields will take.

	var opp = gamedonia.data.createUpdate(query_update, update); // Creates the update operation
	operations_players.push(opp);

	// Invokes bulk operation in the collection "players"
	gamedonia.data.runBulkOperations("players", operations_players, {  

		success: function(result) {  // Success handle for bulk operation
			log.info("players bulk executed successfully");
		},
		error: function(error) { // Error handle for bulk operation
			log.error("Unable to run bulkoperation");
		}
	});

In the code above we are just updating all the entities that match the specified criteria with the same change. If we want to perform different data updates with different matching criterias then we need to build different update operations, add them to the operations list and run the bulk.

Remove

To create a remove operation you just need to create individual operations with the remove criteria. Each operation will match a number of documents that will be removed from the database. You should use this bulk remove when you expect to have a huge impact on the number of documents inside the database. Here's an example on how to do it:

	var operations_players = [];
	var query_remove = "{\”status\”:\”inactive\”}";
	var opp = gamedonia.data.createRemove(query_remove);
	operations_players.push(opp);

	// Invokes bulk operation in the collection "players" 
	gamedonia.data.runBulkOperations("players", operations_players, {  

		success: function(result) {  // Success handle for bulk operation
			log.info("players bulk executed successfully");
		},
		error: function(error) { // Error handle for bulk operation
			log.error("Unable to run bulkoperation");
		}
	});

Callback response

The last important part is the data sent to the callback that can be used to understand the results of the bulk operation execution. The data included in the result object has the following structure:

	{
	 “insertedCount”: 0,
	 “matchedCount”: 0,
	 “modifiedCount”: 0,
	 “removedCount”: 0,
	}

Depending on the executed operations list we will get a different response from the API call.

Function List

This is the whole list of Gamedonia API functions you can access from the server code scripts.

gamedonia

	/**
	  * Calls made after this method call, all ACL permissions will be overriden with read-write permission.
	  * This allows the script to modify data from other users or other collections that the current user does not have permission to read or write.
	  */
	void operateAsMaster();

	/**
	  * Return the normal behaviour of the ACL permission system.
	  */
	void operateAsNormal();

gamedonia.data

	/**
	  * Creates a new EntityData filled with the data of the JSON object passed by the string parameter.
	  */
	EntityData newEntity(String data);

	/**
	  * Creates a new empty EntityData.
	  */
	EntityData newEntity();

	/**
	  * Creates a new ACL permission object.
	  */
	Acl newAcl();

	/**
	  * Adds a new entity to the collection.
	  */
	void create(String collection, EntityData entity, CallbackData callback);

	/**
	  * Removes the selected entity_id from the collection.
	  */
	void remove(String collection, String id, Callback callback);

	void update(String collection, EntityData data, CallbackData callback);

	void update(String collection, String id, Map data, CallbackData callback);

	void get(String collection, String id, CallbackData callback);

	void search(String collection, String query, CallbackDataArray callback);

	void search(String collection, String query, int limit, CallbackDataArray callback);

	void search(String collection, String query, int limit, String sort, CallbackDataArray callback);

	void search(String collection, String query, int limit, String sort, int skip, CallbackDataArray callback);

	void count(String collection, String query, CallbackDataLong callback);

gamedonia.user

	void update(User user, CallbackUser callback);

	void update(Map profile, CallbackUser callback);

	void update(Map profile, boolean overwrite, CallbackUser callback);

	void update(String id, Map profile, CallbackUser callback);

	void update(String id, Map profile, boolean overwrite, CallbackUser callback);

	void get(String userId, CallbackUser callback);

	void search(String query, CallbackDataArray callback);

	void search(String query,int limit, CallbackDataArray callback);

	void search(String query,int limit, String sort, CallbackDataArray callback);

	void search(String query, int limit, String sort, int skip, CallbackDataArray callback);

	void count(String query, CallbackDataLong callback);

gamedonia.push

	void send(String message);

	void send(Map notification, String uid);

In this guide we have learned how to code, run, and debug server side scripts for your game. Follow up with our Server code tutorial, that will teach you how to work with Server Hooks.