Tuesday, 14 March 2023

Read & write multiple User Properties

The following Google Apps Script is a few snippets of some larger code where I needed to write (and then later read back) a number of User Properties in one go. Rather than creating multiple single write requests it is more efficient to do this in bulk.

I also needed a way to bulk read/extract these values later from a JavaScript Object that would allow me to easily call the Property name and get its value in return.

Access User Properties and get the values in an Object
Access User Properties and get the values in an Object


The Code

Putting a number of key:value pairs into User Properties is simple enough via the 'setProperties(properties)' method:

var userProperties = PropertiesService.getUserProperties();
var newProperties = {
   sourceFolderId: '123',
   destinationFolderId: '456',
};
userProperties.setProperties(newProperties);

With regards to getting them back out we can simply reference them directly from the Object:

// log each item from User Properties
Logger.log(userProperties.destinationFolderId);
Logger.log(userProperties.sourceFolderId);

 

Download

Read & write multiple User Properties download (please use 'Overview' > 'Make a copy' for your own version).

5 comments:

  1. Hi Phil - little trick, .getProperties() will return an Object so there is no need to loop over as you can reference directly e.g. Logger.log(userProperties.destinationFolderId); :)

    ReplyDelete
    Replies
    1. Thank you Martin, always happy to learn/improve. I've updated the post / code to reflect this method.

      Ta

      Delete
    2. The official documentation isn't very clear on this one

      Delete
  2. Thank you for the article. Great idea. It is especially relevant if you are struggling to reduce the number of function calls subject to quotas (https://developers.google.com/apps-script/guides/services/quotas#current_limitations/).
    Properties read/write is 50,000/day.
    However, here we may run into another limit: Properties value size is 9 KB/val.
    The way out is to control the size of the property, and if the quota is exceeded, split the property into several parts and load them separately.
    But here the question arises: How to calculate the size of a property in kilobytes?

    ReplyDelete
    Replies
    1. Thank you.

      Good question and honestly not something I've yet come across - as I typically store small/controlled values in the Properties at this time. Somebody else may have a suggestion however ...

      Delete