Executing server code via the Kii Cloud SDK for JavaScript

Here is an example of executing server code via the JavaScript SDK.

// Instantiate the endpoint.
var entry = Kii.serverCodeEntry("main");

// Set parameters.
var arg = {"username":"name_of_my_friend", "password":"password_for_my_friend"};

// Execute the server code.
entry.execute(arg,{

    success: function(entry, argument, execResult) {

      // Parse the result.
      var returned = execResult.getReturnedValue();
      var newUser = returned["returnedValue"];

      // Get the number of the executed steps.
      var steps = execResult.getExecutedSteps();

      // Get the version of Node.js on which the server code was executed.
      var environmentVersion = execResult.getEnvironmentVersion();
    },

    failure: function(entry, argument,execResult, anErrorString) {
      // Handle the error.
    }
  }
);

Here is the brief explanation of the sample code:

  • Creates a KiiServerCodeEntry instance by executing the serverCodeEntry() method with the target endpoint (function) name. You can specify the version of the JavaScript engine for executing the server code with the environmentVersion argument.
  • Prepares custom parameters (the username and password in this sample code) by setting them in a JSON object. Make sure to align the parameter keys with those in the server code so that the server code can properly get the parameter values (in this sample code the keys are "username" and "password").
  • Executes the server code by calling the execute() method with the custom parameters.
    • If there is a logged-in user, Kii Cloud interprets the server code as being executed by this user.
    • If there is no logged-in user, Kii Cloud interprets the server code as being executed by an anonymous user.
  • Gets the result by calling the getReturnedValue() method.
  • (Optionally) gets the number of the executed steps with the getExecutedSteps() method.
  • (Optionally) gets the version of Node.js with the getEnvironmentVersion() method.

The getReturnedValue() method will give you a JSON Object with the result stored in the "returnedValue" field (See Data types of return values for some examples). Use the appropriate method to fetch the actual result; for example, we fetch the newly-created username in the sample code.

If your server code returns the value after the timeout, you can get the value with the getReturnedValue() method likewise. See Timeout for the format of the JSON object you can get with the method.

You cannot execute server code by manually executing another server code. If you attempt to do so, you will get an HTTP 409 response with the "OPERATION_NOT_ALLOWED" error.