This code
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
Logger.log(events);
var sp = PropertiesService.getScriptProperties();
sp.setProperty("events", JSON.stringify(events));
events = JSON.parse(sp.getProperty("events"));
Logger.log(events);
returns:
Info [CalendarEvent, CalendarEvent, CalendarEvent, CalendarEvent, CalendarEvent]
Info [{}, {}, {}, {}, {}]
Why is that? What is wrong?
Why is that?
CalendarEvent
is a Google Apps Script class which events are instances of.Checking property ownership and enumerability yields the following:
What does this tell us?
Object.keys()
).getOwnPropertyNames()
).CalendarEvent
inherits fromObject
1 (seetoString()
).Now, look at what
JSON.stringify()
does for objects (this is a description from MDN, but if you dig into the ECMAScript spec, you will see thatSerializeJSONObject
operation depends on abstractEnumerableOwnPropertyName
):All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized
Which leads us to your second question:
What is wrong?
Since there are no enumerable own properties, the serialization results in
"{}"
.What to do?
It does not make much sense to store events with
PropertiesService
- you will quickly get into quota issues on larger event collections even if you figure a way to store. What does, is to store a reference, so how about usinggetId()
method to store andgetEventById()
to retrieve?Sample
What else to do?
Use the Calendar API (don't forget to enablle it for your GCP project first by going to
Resources
->Cloud Platform project
->APIs and Services
->Library
). This API is a REST API that you can query with good old HTTP requests like that:Note that one would have to set the OAuth scope to be passed with the JWT token (obtained by
getOAuthToken()
). If there is an explicit scope list in application manifest (oauthScopes
field ofappscript.json
), add"https://www.googleapis.com/auth/calendar.events.readonly"
or a more appropriate one.Notes
CalendarEvent
has an object as its prototype due to prototypal inheritance.getUserProperties()
is preferrable togetScriptProperties()
unless a script-wide setup is needed (see official guide in references). Script properties are shared across users and count toward quotas of the script owner.Reference
JSON.stringify()
docs on MDNgetId()
docsgetEventById()
docsPropertiesService
guide