mdho
mdho

Reputation: 51

How to modify global variable (type: array) in handler function

I have an array in the following format:

agendaItems = [{"topic":"blah", "description:"blah"}, {"topic":"blah2", "description":"blah2"}].

I need to update the values in this array in a handler and handler does not allow global variables to be modified. I know I have to use either CacheService or ScriptProperties. However, I can't seem to make it work:

If I use CacheService, I get something like this: "[object oject][object object]"

CacheService.getPublicCache.put('agenda', agendaItems);

If I use ScriptProperties, I get something like this: ""[Ljava.lang.Object;@429bd3a7"

ScriptProperties.setProperty('agenda', agendaItems');

Am I doing this wrong or is there a better way? Any advice is appreciated.

Upvotes: 2

Views: 1034

Answers (1)

megabyte1024
megabyte1024

Reputation: 8650

The Cache class works with strings. You have to use the Utilities.jsonStringify and Utilities.jsonParse methods to convert the array to a string and vice versa. Here is slightly modified code which I use

this.getData = function(id, cacheKey) {
  var cache = CacheService.getPrivateCache();
  var cachedString = cache.get(cacheKey);
  var lstData;
  if (cachedString == null) {
    lstData = getNotCachedData_(id);
    cache.put(cacheKey, Utilities.jsonStringify(lstData));
  }
  else {
    lstData = Utilities.jsonParse(cachedString);
  }
  return lstData;
}

The ScriptProperties Service also works with strings. It is not obvious due to the not complete documentation, the value parameter has type var and not String, but it is true.

Upvotes: 1

Related Questions