jchleb
jchleb

Reputation: 27

Sharing Google Calendar with multiple users via GAS - Loop not working

I am trying to share Classroom calendars with all parents, using GAS. The code copied from the v3/acl resource works to authorize one user, but I can't figure out why my modification to have it loop through the others in the users array is not working. Any help would be appreciated.

The log file reads "User: [email protected], Users.length: 2.0, Cycle: 0.0"

/**
 * Set up calendar sharing for a single user. Refer to 
 * https://developers.google.com/google-apps/calendar/v3/reference/acl/insert.
 *
 * @param {string} calId   Calendar ID
 * @param {string} user    Email address to share with
 * @param {string} role    Optional permissions, default = "reader":
 *                         "none, "freeBusyReader", "reader", "writer", "owner"
 *
 * @returns {aclResource}  See https://developers.google.com/google-apps/calendar/v3/reference/acl#resource
 */
function shareCalendar(calId,user,role) {
  var calId = "[email protected]";
  var users = ["[email protected]","[email protected]"];
  var user = "";
  for (i = 0; i < users.length; i++) {
    var user = users[i];
    role = role || "reader";
    Logger.log('User: %s, Users.length: %s, Cycle: %s',user, users.length,i);

    var acl = null;

    // Check whether there is already a rule for this user
    try {
      var acl = Calendar.Acl.get(calId, "user:"+user);
    }
    catch (e) {
      // no existing acl record for this user - as expected. Carry on.
    }

    if (!acl) {
      // No existing rule - insert one.
      acl = {
        "scope": {
          "type": "user",
          "value": user
        },
        "role": role
      };
      var newRule = Calendar.Acl.insert(acl, calId);
    }
    else {
      // There was a rule for this user - update it.
      acl.role = role
      newRule = Calendar.Acl.update(acl, calId, acl.id)
    }
    return newRule;
  }
}

Upvotes: 0

Views: 202

Answers (1)

Cooper
Cooper

Reputation: 64040

Because it executed a return the first time through loop. Which terminated the execution of the function. That what return does.

return The return statement ends function execution and specifies a value to be returned to the function caller.

Upvotes: 4

Related Questions