Setting Data Automatically with a Trigger-based Hook

It is assumed that this server code is called by a server hook.

This code is aimed to be launched when a new user is created (i.e. when the USER_CREATED trigger is triggered. See Trigger-based Hook for more details on the trigger). We add a KiiObject, representing a randomly-chosen starter item, into the user's "gifts" bucket.

Note that in this example, the parameter of the done() callback function is omitted. This is because there is no way to return the execution result to the client when the server code is triggered by a server hook.

function main(params, context, done) {
  // Get the administrator and the new user.
  var admin = context.getAppAdminContext();
  var user = admin.userWithID(params.userID);

  // Get a gift for the new user.
  var selectedGift = getSignUpGift();

  // Create a bucket and a KiiObject in the user scope.
  var giftObject = user.bucketWithName("gifts").createObject();

  // Set the gift data in the KiiObject.
  giftObject.set("name", selectedGift["name"]);
  giftObject.set("imageUrl", selectedGift["imageUrl"]);

  // Save the KiiObject.{
    success: function(targetObj) {
    failure: function(targetObj, error) {

function getSignUpGift() {

  // Prepare gifts and return one of them randomly.
  var gifts = [{
    "name": "Normal axe",
    "imageUrl": "",
    "hitRate": 70
  }, {
    "name": "Silver axe",
    "imageUrl": "",
    "hitRate": 20
  }, {
    "name": "Golden axe",
    "imageUrl": "",
    "hitRate": 10

  var random = Math.floor(Math.random() * 100);
  var range = 0;
  var selectedGift = gifts[0];
  for (var i=0; i<gifts.length; ++i) {
    range += gifts[i]["hitRate"];
    if (random < range) {
      selectedGift = gifts[i];
  return selectedGift;

Here, we get the app admin context and the ID of the newly-created user with context.getAppAdminContext() and params.userID, respectively. Using this ID, we create a KiiUser instance with the userWithID() method, instantiate the user's gift bucket with the bucketWithName() method and save an item KiiObject into the bucket.