Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

KScript Preview

edited January 2016 in Tutorials
KScript allows you to write custom server logic for Kumulos, in JavaScript. It will be deployed and accessed in the same way as your existing API methods but offers you much greater flexibility and control over what happens on the server.

This document outlines the current capabilities and caveats of the implementation.

We hope you enjoy using KScript in your applications, and we'd love to hear your feedback on it. Please feel free to send an email to with any suggestions.

Getting Started

You create KScripts from the API tab of your application in Kumulos. Underneath the "Create API" button, there will be a "Create Some KScript" button if it's enabled on your account.

The KScript Editor

The familiar three steplets are carried over from the existing API creator. Firstly you define a method title, and you tell kumulos whether you'll be returning objects (database records for example), or a number.

Next you can add typed input parameters to the method. Each parameter should have a name and a type set for it. These parameters will be available to use from your KScript code.

Finally there is a code entry box and toolbar. The toolbar provides the ability to insert the aliases of tables or other API methods (which can be hard to remember) and some buttons to save, run, and view the code in full screen.

The Esc key will toggle full screen editing when the code editor has focus.

KScript Reference

KScript has access to the parameters posted to the script, and a library of useful functions which can be used whilst writing your scripts. These methods are all exposed through the global variable K.


K.params will give you access to the parameters posted to your script. For example, a parameter called userID would be referenced as:K.params.userID.

K.params.has(key) will tell you if there is a non-empty value passed for the given key.


It is possible to log information to a debugging console during development of your KScripts. This can be useful for seeing what's going on at runtime. To log information to the debugging console, call K.log with any value you want to log out. It will accept a variable number of arguments and will show them as an array in the debug log.


This function is designed to log any arguments passed to it and also log a stack trace. It will also print the function that called the .error() method.This can be useful for tracing errors in KScripts.


Calling this method will output a stack trace of function names and line numbers called up to this point.

K.callAPIMethod(alias, paramsObject)

This method allows you to call existing API methods from inside the KScript, and then operate on the results. For example:

var results = K.callAPIMethod('getUserByID', {userID, K.params.userID});
// Do stuff with the results


This is how a KScript returns data to the API endpoint. You can pass objects, arrays of objects, or numbers to this method. For example:

var users ='users').run();

N.B. This method does not halt execution of the script, so you should plan to generate a result object and set it as the response at the end of execution.


This function can be used to check for failure of any database operations. It returns true or false depending on if the call failed or not.


You can include other KScript files at runtime with the include function. Any functions or global variables inside the included KScript file will be loaded into the current scope. For example:

// In _init_ KScript method
function init() {

// In doSomething KScript method


If you want to halt execution on an error, you can throw an exception:

var results = false;
if (failed(results)) {
throw "Results failed!";

Hashing Functions

KScript has md5() and sha1() available as global functions. These should be faster than JavaScript implementations of these functions.

Database Operations

K.query(sql, parameters)

This function allows you to run custom queries on your database. Queries should be written in the MySQL syntax and should use placeholders where you wish to use a value passed as a parameter. For example, if selecting a user by userID, you could use:
var results = K.query("SELECT * FROM users WHERE userID=?", [K.params.userID]);

Parameters will be bound in order, and the second argument must be an array. If you don't use any placeholders in your query then you should pass an empty array, like so: []. will return a select action object that can be used to query tables in the database. For example:

var select ='users').filter('userID', K.params.userID);
var results =;

Alternatively you can chain the .run() call:

var results ='users').filter('userID', K.params.userID).run();


It is possible to use the .filter() method on select, update and delete action objects to filter the data each action will operate on. Multiple filters can be chained together (in logical AND) by chaining calls, like: .filter('userID', K.params.userID).filter(...)

Alternatively, you can pass an object of filters to be applied like so: .filter({userID: K.params.userID, field: K.params.value})

The filter method returns the original select object so you can chain on a call to run() if you want.


With the select action, it's possible to sort the records with a call to .sort(field, direction). field must be the alias of a field in the table, and direction must be one of 'ASC' for ascending or
'DESC' for descending.

Result Handling

In the case of K.query and, they return array-like objects which can be iterated through or returned as responses. This is done like so:

var users ='users').run();
for (var user = null; users.hasNext(); user = {
// Do something with user
// Set properties?
user.someRandomNumber = Math.random();
// All user objects in users will have a random number attached

In addition to iteration, the result array also supports the following properties and methods:


<b>K.insert(table, object)</b>

This method creates a record in the database and returns the ID of the newly created record. For example:

var userID = K.insert('users', {username: K.params.username});

<b>K.update(table, object)</b>

To update records, use this method. It can have filters chained on to it just as If you're updating, do remember to define filters. An example to update a user:

var result = K.update('users', {username: K.params.username}).filter('userID', K.params.userID).run();
The result is the number of updated records, not the number of matching records. So if you call an update and there's nothing to change, it will return 0.


This method allows you to delete records from a table. If you call it with no filters, it will not run unless you also call .forceDeleteAll(). For example:

// Will run
var deleteUser = K.delete('users').filter('userID', K.params.userID).run();
// Will throw an exception to the log
var deleteAllUsers = K.delete('users').run();
// Will run
var deleteAllUsers = K.delete('users').forceDeleteAll().run();
This method returns the number of records deleted.


KScript introduces persistent sessions to Kumulos and allows you to use them in your apps. KScript sessions are in-memory key-value stores which are designed to be fast and simple to use.


This method returns true if the session has a non-empty value for the given key.


If you need to unset a session variable, you can use this method. Subsequent accesses to the session key after removing it will return null.


All session values stored for the user's session will be deleted.

By default, session values will persist for one hour after the session was last accessed.


To access and set values in the session, you can use this object. It behaves like the K.params object, but it allows setting values too. For example:

var response = 0;
if (!K.session.has('userID')) {
var results ='users').filter({
username: K.params.username,
passwordHash: K.params.hashedPassword
if (!failed(results) && results.length == 1) {
K.session.userID = results.itemAtIndex(0).userID;
response = 1;
else {
response = 0;
else {
// Already logged in
response = 1;

Facebook SDK

It is possible to use the Facebook SDK through KScript. This is designed to aid you in building Facebook apps with Kumulos. In order to use the SDK in KScript you need to initialise it.

K.initFB(appID, appSecret, userAccessToken)

This initialisation method sets up the Facebook SDK for use in your KScript. You need to pass in your facebook app details along with a valid user access token. This access token can be retrieved from a logged in user by using one of Facebook's various SDKs. With those items, you can initialise KScript's Facebook SDK like so:

var FB_APP_ID = '';
var FB_APP_SECRET = '';
K.initFB(FB_APP_ID, FB_APP_SECRET, K.params.fbAccessToken);

We recommend storing the access token in the KScript session after a successful login action.

It also makes sense to store this initialisation in a KScript you can include whenever you need access to the Facebook SDK.


After initialisation, the api() method can be used to query the Facebook graph API as the currently logged in user, in accordance with the permissions the user has granted your app. The results it returns are dependant on the query you issue.

This method may throw exceptions if the call fails for some reason (insufficient priviledges or an expired access token for instance). You can catch these by using JavaScript's try
{} catch (e) {} construct.

You can learn more about the Graph API in the

An example that retrieves the user's profile information is shown:

// In setFacebookAccessToken
K.session.fbAccessToken = K.params.fbAccessToken;

// In _facebook_
var FB_APP_ID = '';
var FB_APP_SECRET = '';
// Assume session storage of access token set by setFacebookAccessToken
K.initFB(FB_APP_ID, FB_APP_SECRET, K.session.fbAccessToken);

// In getFacebookProfile
var userProfile = K.FB.api('/me');


This method returns the currently logged in user's FBUID. The logged in user is determined by the currently initialised access token passed to K.initFB().

Known Issues

Unterminated strings in a KScript will result in "Built undefined API methods" and break the deployment process (look for unterminated strings in your code to fix this issue)

include(alias) currently has no guards on cyclic includes and as such, methods may crash unexpectedly if the same script is included twice
The syntax checker is a little bit too aggressive and complains about almost everything (but it will still run fine)
Building from the KScript editor will ignore your chosen deployment platforms
Renaming KScript methods won't check that the name is available first, so you can have two methods with the same name
Using a ? placeholder for integer parameters (such as those passed to LIMIT SQL statements) doesn't work because it adds quotes to the integer value. As a workaround, you can use string concatenation in your query and parseInt on the input parameter to check it is sensible.
Occasionally KScript may return completely empty responses. This is fairly uncommon and if you experience it, please submit the code you were using along with a bug report.
Entering a multiline string with a space after the escape character (\) will crash the browser tab
Reporting Bugs

Please send any bug reports to and include as much information as possible about how to reproduce the error.
Sign In or Register to comment.