10 Best Practices for Google Apps Script - White Stratus May 15, 2014

Page created by Christine Austin
 
CONTINUE READING
10 Best Practices for Google Apps Script - White Stratus May 15, 2014
10 Best Practices for
Google Apps Script
White Stratus • May 15, 2014
10 Best Practices for Google Apps Script                                 Page 2 of 8

Overview
Apps Script is a scripting language created by Google to allow developers to
extend the functionality of Google Apps and Sites. Its basis in JavaScript provides
an easy runway for developers to integrate Docs, Sheets and Sites with Google
APIs and third-party services.

With Apps Script you can easily:

 • add custom menus, dialogs, and sidebars to Google Docs, Sheets,
   and Forms (Add-ons)

 • write custom functions for Google Sheets

 • publish web apps — either standalone or embedded in Google Sites (Gadgets)

 • interact with other Google services, including AdSense, Analytics, Calendar,
   Drive, Finance, Gmail, and Maps

You can see more examples in the Google Developers Showcase.

Here at White Stratus, we help our clients tap into the power of Google Apps
Script every day. Some time saving and productivity enhancing ideas from our
own applications and clients include:

 • Converting a data sheet into a column of JSON objects for an
   application to use

 • Automatically creating structured team collaboration environments

 • Creating common Drive folders and document template files

As with all components of the Apps platform, there is nothing to install. Google
provides the code editor in the browser, and your scripts run on Google Apps
cloud infrastructure.

To save you some time, and help you avoid frustration, we’re sharing our top ten
list for Apps Script developed Gadgets, Add-Ons and Web Apps.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
10 Best Practices for Google Apps Script                                  Page 3 of 8

1. Listen to Google’s Best Practices
Okay, we may be cheating a bit here but we cannot discount the extensive list of
best practices Google has already assembled from its own internal and external
user community.

The highlight from Google’s list: practices we have found to be especially
noteworthy and deserve a reprint include:

 • Reduce the number of API Calls

 • When making API calls batch the requests

 • Use the Apps Script built-in cache service

 • Do not use UIApp; use HTMLService

For more information, you can find their invaluable list here.

2. Do Not Assume You Can Import JavaScript Libraries
Most libraries will not make it past the Google Apps Script’s Caja compiler.

Why? Caja is the security blanket designed to prevent the misuse of Apps Script
by sanitizing any attempts to run malicious software on Google’s Servers.
Unfortunately, it also prevents most libraries from being able to be included in
your application.

Be ready to write all the functionality yourself as you will not be able to rely on
an Apps Script library unless by some small chance this has already been created
by another developer.

3. Use Apps Script Libraries Sparingly or Not at All
Apps Script does have the ability to load other Apps Script files as libraries and
also provides a rudimentary versioning system. This feature is great, but it also
increases the load time as the library must be loaded before any code can
be read.

Remember: you have a 5 minute window. It may not make sense to waste it
by loading libraries.

If possible, avoid using libraries altogether and instead, write the necessary code
yourself. Although this solution may take a bit longer in the development phase,
ultimately the finished code will provide the best performance possible. In
many cases, you are actually not using everything within a library, so picking and
choosing the parts you need and then coding it yourself will both increase the
code performance and decrease the code load time.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
10 Best Practices for Google Apps Script                                       Page 4 of 8

4. Dynamically Create the HTML
Templated HTML is a powerful and easy way of mixing Apps Script code and
HTML to produce dynamic pages with minimal effort. However, remember that
this, too, will increase your script load time.

The script clock is always ticking, and anything you can do to reduce run time will
benefit your scripts - instead, try to make run.google.script calls and dynamically
create HTML with jQuery on $(document).ready, for example:

  {
      var HtmlString = ‘’;
      var folder = Drive.Files.get(folderId);

   //Building HTML
   HtmlString += ‘’ + ‘’+folder.title+’’; //title

  // DO SOMETHING WITH THE TITLE //

  }

5. Remember You Have 5 Minutes (max)
Apps Script runs on Google servers and is free to use, however - because of this
fact - Google places limits on the amount of processing a single Apps Script file
can complete at a time and per day.

This means your script needs to capitalize on efficiency!

Rendering the UI should always be as fast as possible (you do not want to keep
the user waiting), but equally important is the speed of your backend processing
which should be a priority.

If you happen to exceed Google’s 5 minute time limit, your script will
terminate immediately without notification. This event can be problematic
for troubleshooting and debugging, so we recommend including triggers in
potentially resource intensive scripts and subscribing to notifications for
that trigger.

For more detailed advice for time triggering your scripts see
8. Keep Track of the Time.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
10 Best Practices for Google Apps Script                                  Page 5 of 8

6. Adhere to Google’s HTMLService Best Practices
HTML services “serve” web pages that can interact with server-side Apps Script
functions. You might use them when building web apps or adding custom user
interfaces in Google Docs, Sheets and Forms.

The highlights from Google’s list: practices we have found to be especially
noteworthy and deserve a reprint include:

 • Separate HTML, JavaScript, and CSS

 • Load data asynchronously, not in templates

 • Don’t use , , or  tags

 • Load JavaScript last

For more information, you can find their invaluable list here.

7. Use Advanced Services Where Possible
Apps Script has its own Java-based GET and SET functions for the majority of
Google APIs (“Google Apps Services”), but it is also worth considering the use
of Google Advanced services. We recommend using the Advanced services
whenever possible because they are usually the latest version and connect to a
Cloud Console Project that can then be monitored.

Be aware that using the built-in services does require extra overhead behind the
scenes which can occasionally cause issues. With a little extra effort on your part,
however, you can build in a more robust error catching and exponential backoff
retry system that will allow you to have increased control over errors and their
handling (see 8. Keep Track of the Time for more information on handling time).

To illustrate with an example, the DocsList and DriveApp Google Apps Services
both do basically the same thing to provide access to Google Drive APIs,
however, DocsList is based on the deprecated Docs Feed and DriveApp is based
on the newer Drive APIs. Both of these are Google Apps Services which do not
provide full access to the Drive APIs - instead, use the Advanced Drive Service
that will grant full access to the APIs and still works with autocomplete.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
10 Best Practices for Google Apps Script                                    Page 6 of 8

DocsList is experimental and based on the deprecated Documents List APIs -
as illustrated by the following:

 • Google Apps Services

   Calendar

   Contacts

   DocsList (Experimental)

   Document

   Domain (Experimental)

   Drive

  Google Documents List API version 3.0

  Important: Version 3.0 of the Google Documents List API has been officially
  deprecated as of September 14, 2012. It will continue to work as per our
  deprecation policy, but we encourage you to move to the Google Drive API.

The DriveApp APIs have limitations such as sharing programmatically: sharing a
Google Drive file with a group of users will automatically email the newly added
users to inform them that they have access. Keep in mind that there is no way
to prevent this email, even though the underlying APIs provide the functionality
to turn notifications on or off. Despite the settings, the Advanced service gives
direct overriding access to the APIs.

8. Keep Track of the Time
As we mentioned earlier, free has time limits – for Apps Script that is 5 minutes.
Once a script has exceeded that time limit, Google stops its execution, which can
leave your processes in a very unhappy state.

To avoid any confusion, create a global variable that captures the time the App
Script starts. If the Apps Script is doing heavy processing, try to break it up into
sections and do several tests to figure out the average time it takes for
each section.

Make sure there is enough time remaining since the app started before starting
each new section. If there is not enough time, log where in the section the script
stopped in Script Properties and start from that point the next time.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
10 Best Practices for Google Apps Script                                  Page 7 of 8

For example:

  {
       var currentExecutionTime = new Date().getTime() - _START_TIME_;
      // Time spent so far in milliseconds

    for(var i=1; i
10 Best Practices for Google Apps Script                                                Page 8 of 8

(BONUS!) Passing Parameters for Gadgets
With Apps Script, you can easily capture settings for Apps Script gadgets by
passing parameters. This method can be used for XML gadgets for Google Sites
or as a content service.

As an example, make a call to the Apps Script file with some parameters that are
crunched and ultimately returned as finished data that any application can then
call. To pass the parameters, you’ll need to use the doGet function and then edit
the App Script URL.

  function doGet(e)
  {
  var yourParameter = e.parameter.param;
  }

Next, the resulting service URL you will receive from Apps Script when publishing
needs to be edited to allow parameters to be passed through the URL, as follows:

You will get this format back:

https://script.google.com/a/macros/mydomain.com/s/A1Z5Ri7QL9fi7yJ5cU3/exec

You will need to change the URL to this format:

https://sites.google.com/a/macros/mydomain.com/
exec?service=A1Z5Ri7QL9fi7yJ5cU3&param=4

You Are Now Ready to Build Faster, Better
and More Robust
You are now ready to change the world (for good of course) with Google’s App Script.

If you find you need additional expertise - the White Stratus team is here to help
build the right application for your unique business challenges on Google’s leading
cloud infrastructure - contact us at www.whitestratus.com.

  About White Stratus

  White Stratus is a leading provider of software development, system integration, and
  business consulting services to help large enterprises realize the benefits of the Google
  Cloud. White Stratus has offices in New York, London, Amsterdam, Tokyo, Sydney, and
  Toronto. For more information visit www.whitestratus.com.

White Stratus | New York | London | Dublin | Amsterdam | Tokyo | Sydney | Toronto
                            email: info@whitestratus.com
You can also read