google-apps-scriptgoogle-admin-sdk

Find and read resource calendars in Admin Directory


Context
During a form POST for booking a hotel, I first want to check if we have free rooms in our apartments. I created Resource calendars (with buildings, etc.) via the GSuite admin panel.

Now I am testing a bit with some code I found on this site. It finds the resource calendars and I simply filter them by name (to get rid of all the meeting rooms). But now I would like to "read" the calendar itself. But it seems the resourceId is not the id of the respective resource calendar.

How can I check the availability in the resource calendar?

do {
  var arguments = {
    maxResults: 200,
    pageToken: pageToken
  }; 
  calendars = AdminDirectory.Resources.Calendars.list("my_customer", arguments);
  if (calendars.items && calendars.items.length > 0) {
    for (var i = 0; i < calendars.items.length; i++) {
      var calendar = calendars.items[i];
      if (calendar.buildingId.substr(0, 9).toUpperCase() === "APARTMENT" ) {
        Logger.log('YES %s (ID: %s) (%s),', calendar.resourceId, calendar.resourceName, calendar.buildingId);  

        // 
        // The code below doesn't work (null reference). But I would to do something like this.
        //
        var resourceCalendar = CalendarApp.getCalendarById(calendar.resourceId);
        Logger.log("I found the following calendar %s ", resourceCalendar.getName() );

      }
    }
  } else {
    Logger.log('No calendars found.');
  }
  pageToken2 = calendars.nextPageToken;
} while (pageToken); 

Solution

  • I tried this code and it works.

    Note that I used the email resource as ID for CalendarApp

    function myFunction() {
      var pageToken;
      do {
        var arguments = {
          maxResults: 200,
          pageToken: pageToken
        }; 
        calendars = AdminDirectory.Resources.Calendars.list("my_customer", arguments);
        if (calendars.items && calendars.items.length > 0) {
          for (var i = 0; i < calendars.items.length; i++) {
            var calendar = calendars.items[i];
            Logger.log('resource name : '+calendar.resourceName);  
    
            //Logger.log('resource data : '+JSON.stringify(calendar)+'\n');// this is useful to see what we get  
    
            var resourceCalendar = CalendarApp.getCalendarById(calendar.resourceEmail);
            if(resourceCalendar){
              Logger.log("I found the following calendar %s \n", resourceCalendar.getName() );
            }else{
              Logger.log('ressource skipped- undefined ----------------');
            }
          }
        }
      } while (pageToken); 
    }