Manually Executing Server Code

You can also execute your Server Code directly at any time from the client side. When you directly execute the Server Code, you can also pass some custom parameters.

Let's explore how you can manually execute the Server Code. Let us assume that you've deployed the following Server Code.

function main(params, context, done) {
  var user = KiiUser.userWithUsername(params.username,
                                      params.password);
  user.register({
    success: function(user) {
      done(user.getUsername());
    },
    failure: function(user, errorString) {
      done(errorString);
    }
  });
}

This is the same sample code we've presented in Writing your Server Code. The sample code is expecting to receive a username and password from a client device as the custom parameter, and it will execute the sign-up process with these parameters (e.g. "allowing an application user to sign-up on behalf of his/her friend).

Note that the success/failure status within the Server Code doesn't match that on the client. In this sample code, the call from the client will be successful even if the process within the Server Code fails because the client will receive the error string successfully. The client will fail when it cannot call the Server Code. Implement codes to return the success/failure status of the Server Code as the return value in order to send the error on the Server Code to the client.

Executing Server Codes via REST API

Here is an example of executing the sample Server Code via the REST API.

curl -v -X POST \
  -H "Authorization: Bearer {ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  "https://api.kii.com/api/apps/{APP_ID}/server-code/versions/current/main" \
  -d '{"username": "name_of_my_friend", "password": "password_for_my_friend"}'
  • We are passing the values for "username" and "password" as the data.
  • We are calling the API with the target endpoint ("main").
  • The access token is optional. If omitted, Kii Cloud will handle that the Server Code is executed by an anonymous user.

This will execute the function "main" in the Server Code. As you see in the sample Server Code, two custom parameters are used in the KiiUser.userWithUsername method. Notice that the code is using the keys ("username" and "password") when fetching the corresponding values.

The response will be like the followings:

< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Access-Control-Allow-Origin: *
< X-Step-count: 3
< Content-Type: application/json;charset=UTF-8
< Cache-Control: max-age=0
< Content-Length: 27
< Accept-Ranges: bytes
< Date: Tue, 23 Jul 2013 03:57:28 GMT
< X-Varnish: 1572330455
< Age: 0
< Via: 1.1 varnish
< Connection: keep-alive
<
* Connection #0 to host js-box-tmp.internal.kii.com left intact
{"returnedValue":"name_of_my_friend"}
* Closing connection #0

You can see that the execution result is returned in the "returnedValue" field. Also, the number of the executed steps is returned in "X-Step-count" header.

Your Server Code can return other data types as the execution result. Please check the following table to see how the execution result is returned to the client. (Here we assume that the name of callback function for returning the result is "done" in the asynchronous mode).

Statement in the synchronous code Statement in the asynchronous code Return value in the response
return 1; done(1); {"returnedValue":1}
return "resp"; done("resp"); {"returnedValue":"resp"}
return true; done(true); {"returnedValue":true}
return {name:"Kii", zip:"123456"}; done({name:"Kii", zip:"123456"}); {"returnedValue":{name:"Kii", zip:"123456"}}
return ["one", "two"]; done(["one", "two"]); {"returnedValue":["one", "two"]}

Timeout

As described in the Limitations, the timeout occurs when the server code execution time goes over 20000 msec.

When the timeout occurs, Kii Cloud usually returns a 400 response as follows:

{
  "errorCode" : "ENDPOINT_INVOCATION_ERROR",
  "message" : "Error found while executing the developer-defined code",
  "details" : {
    "errorCode" : "EXECUTION_TIMEOUT",
    "message" : "execution timeout. limit=20000ms"
  }
}

If you've set the value to return after the timeout as described in Server Code Syntax, you will get a 200 response instead of a 400 response. In this case, the value specified in the server code will be set in the _timeoutResponse as follows:

{
  "returnedValue":{
    "_timeoutResponse":{
      "customField": "my_custom_message"
    }
  }
}

You can get the value just like the normal execution result.

Executing Server Codes via Android SDK

Here is an example of executing the sample Server Code via the Android SDK.

  • // Instantiate with the endpoint.
    KiiServerCodeEntry entry = Kii.serverCodeEntry("main");
    
    try {
      JSONObject rawArg = new JSONObject();
    
      // Set the custom parameters.
      rawArg.put("username", "name_of_my_friend");
      rawArg.put("password", "password_for_my_friend");
      KiiServerCodeEntryArgument arg = KiiServerCodeEntryArgument
          .newArgument(rawArg);
    
      // Execute the Server Code
      KiiServerCodeExecResult res = entry.execute(arg);
    
      // Parse the result.
      JSONObject returned = res.getReturnedValue();
      String newUser = returned.getString("returnedValue");
    
      // Get the number of the executed steps.
      int steps = res.getExecutedSteps();
    
    } catch (AppException e) {
      // Handle the error.
    } catch (IOException e) {
      // Handle the error.
    } catch (JSONException e) {
      // Handle the error.
    }
  • // Instantiate with the endpoint.
    KiiServerCodeEntry entry = Kii.serverCodeEntry("main");
    
    JSONObject rawArg = new JSONObject();
    try {
      // Set the custom parameters.
      rawArg.put("username", "name_of_my_friend2");
      rawArg.put("password", "password_for_my_friend");
    } catch (JSONException e) {
      // Handle the error.
    }
    KiiServerCodeEntryArgument arg = KiiServerCodeEntryArgument
        .newArgument(rawArg);
    
    // Execute the Server Code
    entry.execute(arg, new KiiServerCodeEntryCallback() {
      public void onExceuted(KiiServerCodeEntry entry, KiiServerCodeEntryArgument argument,
                             KiiServerCodeExecResult res, Exception exception) {
        if (exception != null) {
          // Handle the error.
          return;
        }
        // Parse the result.
        try {
          JSONObject returned = res.getReturnedValue();
          String newUser = returned.getString("returnedValue");
    
          // Get the number of the executed steps.
          int steps = res.getExecutedSteps();
        } catch (JSONException e) {
          // 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.
  • Prepares custom parameters (the username and password in this sample code) by setting them in a JSON Object and by creating a KiiServerCodeEntryArgument with the newArgument method. 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 that this user executes the Server Code.
    • If there is no logged-in user, Kii Cloud interprets that an anonymous user executes the Server Code.
  • Gets the result by calling the getReturnedValue method.
  • (Optionally) gets the number of the executed steps with the getExecutedSteps method.

The getReturnedValue method will give you a JSON Object with the result stored in the "returnedValue" field (please check here for some examples). Please use the appropriate method to fetch the actual result; for example, we are fetching the newly-created username with getString in the sample sample code.

If your server code returns the value after the timeout, you can get the value with the getReturnedValue method likewise. Please check here for the format of the JSON object you can get with the method.

Executing Server Codes via iOS SDK

Here is an example of executing the sample Server Code via the iOS SDK.

Objective-C:

  • // Instantiate with the endpoint.
    KiiServerCodeEntry* entry =[Kii serverCodeEntry:@"main"];
    
    // Set the custom parameters.
    NSDictionary* argDict= [NSDictionary dictionaryWithObjectsAndKeys:
                             @"name_of_my_friend", @"username",
                             @"password_for_my_friend", @"password", nil];
    KiiServerCodeEntryArgument* argument= [KiiServerCodeEntryArgument argumentWithDictionary:argDict];
    
    // Execute the Server Code.
    NSError* error = nil;
    KiiServerCodeExecResult* result = [entry executeSynchronous:argument
                                                      withError:&error];
    if (error != nil) {
      // Handle the error.
      return;
    }
    
    // Parse the result.
    NSDictionary *returnedDict = [result returnedValue];
    NSString *newUser = [returnedDict objectForKey:@"returnedValue"];
    
    // Get the number of the exectued steps.
    int execSteps = (int)[result executedSteps];
  • // Instantiate with the endpoint.
    KiiServerCodeEntry* entry =[Kii serverCodeEntry:@"main"];
    
    // Set the custom parameters.
    NSDictionary* argDict= [NSDictionary dictionaryWithObjectsAndKeys:
                             @"name_of_my_friend", @"username",
                             @"password_for_my_friend", @"password", nil];
    KiiServerCodeEntryArgument* argument= [KiiServerCodeEntryArgument argumentWithDictionary:argDict];
    
    // Execute the Server Code.
    NSError* error = nil;
    [entry execute:argument
         withBlock:^(KiiServerCodeEntry *entry, KiiServerCodeEntryArgument *argument, KiiServerCodeExecResult *result, NSError *error) {
      if (error != nil) {
        // Handle the error.
        return;
      }
      // Parse the result.
      NSDictionary *returnedDict = [result returnedValue];
      NSString *newUser = [returnedDict objectForKey:@"returnedValue"];
    
      // Get the number of the exectued steps.
      int execSteps = (int)[result executedSteps];
    }];

Swift 2.3:

  • let entry = Kii.serverCodeEntry("main")
    let argDict = ["username":"name_of_my_friend","password":"password_for_my_friend"]
    let argument = KiiServerCodeEntryArgument(dictionary:argDict)
    
    let result : KiiServerCodeExecResult
    do{
      result = try entry.executeSynchronous(argument)
    }catch(let error as NSError){
      // Handle the error.
      return
    }
    // Parse the result.
    let returnedDict = result.returnedValue()
    let newUser = returnedDict?["returnedValue"];
    
    // Get the number of the exectued steps.
    let execSteps : Int = result.executedSteps()
  • let entry = Kii.serverCodeEntry("main")
    let argDict = ["username":"name_of_my_friend","password":"password_for_my_friend"]
    let argument = KiiServerCodeEntryArgument(dictionary:argDict)
    entry.execute(argument) { (retEntry : KiiServerCodeEntry, retArg : KiiServerCodeEntryArgument?, result : KiiServerCodeExecResult?, error : NSError?) in
      if error != nil {
        // Handle the error.
        return
      }
      // Parse the result.
      let returnedDict = result?.returnedValue()
      let newUser = returnedDict?["returnedValue"];
    
      // Get the number of the exectued steps.
      let execSteps : Int = result!.executedSteps()
    }

Swift 3:

  • let entry = Kii.serverCodeEntry("main")
    let argDict = ["username":"name_of_my_friend","password":"password_for_my_friend"]
    let argument = KiiServerCodeEntryArgument(dictionary:argDict)
    
    let result : KiiServerCodeExecResult
    do{
      result = try entry.executeSynchronous(argument)
    }catch(let error as NSError){
      // Handle the error.
      return
    }
    // Parse the result.
    let returnedDict = result.returnedValue()
    let newUser = returnedDict?["returnedValue"];
    
    // Get the number of the exectued steps.
    let execSteps : Int = result.executedSteps()
  • let entry = Kii.serverCodeEntry("main")
    let argDict = ["username":"name_of_my_friend","password":"password_for_my_friend"]
    let argument = KiiServerCodeEntryArgument(dictionary:argDict)
    entry.execute(argument) { (retEntry : KiiServerCodeEntry, retArg : KiiServerCodeEntryArgument?, result : KiiServerCodeExecResult?, error : Error?) in
      if error != nil {
        // Handle the error.
        return
      }
      // Parse the result.
      let returnedDict = result?.returnedValue()
      let newUser = returnedDict?["returnedValue"];
    
      // Get the number of the exectued steps.
      let execSteps : Int = result!.executedSteps()
    }

Here is the brief explanation of the sample code:

  • Creates a KiiServerCodeEntry instance by executing the serverCodeEntry method with the target endpoint (function) name.
  • Prepares custom parameters (the username and password in this sample code) by setting them in an NSDictionary and by creating a KiiServerCodeEntryArgument with the argumentWithDictionary method. 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 executeSynchronous method with the custom parameters.
    • If there is a logged-in user, Kii Cloud interprets that this user executes the Server Code.
    • If there is no logged-in user, Kii Cloud interprets that an anonymous user executes the Server Code.
  • Gets the result by calling the returnedValue method.
  • (Optionally) gets the number of the executed steps with the executedSteps method.

The returnedValue method will give you an NSDictionary with the result stored in the "returnedValue" key (please check here for some examples). Please use the appropriate method to fetch the actual result.

If your server code returns the value after the timeout, you can get the value with the returnedValue method likewise. Please check here for the format of the NSDictionary you can get with the method.

Executing Server Codes via Unity SDK

Here is an example of executing the sample Server Code via the Unity SDK.

// Instantiate with the endpoint.
KiiServerCodeEntry entry = Kii.ServerCodeEntry("main");

JsonObject rawArg = new JsonObject();

// Set the custom parameters.
rawArg.Put("username", "name_of_my_friend");
rawArg.Put("password", "password_for_my_friend");
KiiServerCodeEntryArgument arg = KiiServerCodeEntryArgument
    .NewArgument(rawArg);

// Execute the Server Code
entry.Execute(arg, (KiiServerCodeEntry retEntry, KiiServerCodeEntryArgument args,
                    KiiServerCodeExecResult result, Exception e) => {
  if (e != null)
  {
    // Handle the error.
    return;
  }
  // Parse the result.
  JsonObject returned = result.ReturnedValue;
  string newUser = returned.GetString("returnedValue");

  // Get the number of the executed steps.
  int steps = result.ExecutedSteps;
});

Here is the brief explanation of the sample code:

  • Creates a KiiServerCodeEntry instance by executing the ServerCodeEntry method with the target endpoint (function) name.
  • Prepares custom parameters (the username and password in this sample code) by setting them in a JSON Object and by creating a KiiServerCodeEntryArgument with the NewArgument method. 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 that this user executes the Server Code.
    • If there is no logged-in user, Kii Cloud interprets that an anonymous user executes the Server Code.
  • Gets the result by the ReturnedValue property.
  • (Optionally) gets the number of the executed steps with the ExecutedSteps property.

The ReturnedValue property will give you a JSON Object with the result stored in the "returnedValue" field (please check here for some examples). Please use the appropriate method to fetch the actual result; for example, we are fetching the newly-created username with GetString in the sample code.

If your server code returns the value after the timeout, you can get the value from the ReturnedValue property likewise. Please check here for the format of the JSON object you can get with the method.

Executing Server Codes via JavaScript SDK

Here is an example of executing the sample Server Code via the JavaScript SDK.

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

// Set the custom 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) {
      // do something now that the user is logged in

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

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

    failure: function(entry, argument,execResult, anErrorString) {
      // do something with the error response
    }
  });

Here is the brief explanation of the sample code:

  • Creates a KiiServerCodeEntry instance by executing the serverCodeEntry method with the target endpoint (function) name.
  • Prepares custom parameters (the username and password in this sample code) by setting them in an 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 that this user executes the Server Code.
    • If there is no logged-in user, Kii Cloud interprets that an anonymous user executes the Server Code.
  • Gets the result by calling the getReturnedValue method.
  • (Optionally) gets the number of the executed steps with the getExecutedSteps method.

The getReturnedValue method will give you a JSON Object with the result stored in the "returnedValue" field (please check here for some examples). Please use the appropriate method to fetch the actual result; for example, we are fetching 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. Please check here for the format of the JSON object you can get with the method.

Executing Server Codes via Thing SDK Embedded

You can execute server codes from the thing by using the Thing SDK Embedded. See Executing Server Codes to learn how to execute server codes.