google-apps-scriptcachingurlfetch

How can I cache an object in Google Apps scripts


I am fetching JSON data from JIRA in a script for a spreadsheet in Google Drive. I have a script that does the fetch just fine, and I am pretty much only fetching the data for the issue. What I get back is JSON text field representing all the data about that particular JIRA issue.

Instead of making the call to the UrlFetch Service everytime I want one of the fields from a particular JIRA issue, I would like to cache the fetched JSON data after the first fetch.

Unfortunately, Google's Cache service for Google Apps scripts will only cache data in string format, and limits the string to 200 characters. The JSON text data that comes back from JIRA is far in excess of 200 characters.

Is there an alternate way of caching a javascript object like a parsed JSON string or a way to cache more than 200 characters in Google Apps scripts?

This is the code where I tried to cache the data before I realized it was stored as a string:

function _fetchJiraData(targetIssue) {
  Logger.log("Started fetching JIRA data for '%s'", targetIssue);
  
  var data = cache.get(targetIssue);
  if (data == null) {
    var options = {
      headers : {
        Authorization : "Basic " + Utilities.base64Encode('user:password')
      }
    };
    var url = Utilities.formatString(
      'https://rentrak.atlassian.net/rest/api/latest/issue/%s',
      targetIssue
    );
    var result = UrlFetchApp.fetch(url, options);
    var jsonText = result.getContentText();
    data = JSON.parse(jsonText);
    
    cache.put(targetIssue, data);
  }
    
  // TODO: validate data
  return data;
};

Solution

  • Apps Script Cache Service can cache up to 100KB per key, you should not have an issue with only "200" characters. The tighter limitation is only for the key, which is 250 characters.

    The main issue I see with your code is that you're trying to cache the parsed data, instead of the text. Unless your keys are that big (in which case I recommend you used a enconding instead), this should work:

    function _fetchJiraData(targetIssue) {
      var jsonText = cache.get(targetIssue);
      if (jsonText === null) {
        //...prepare your fetch
        var result = UrlFetchApp.fetch(url, options);
        jsonText = result.getContentText();
        cache.put(targetIssue, jsonText);
      }
    
      var data = JSON.parse(jsonText);
      return data;
    }