Creating a namespace-like organization in a google apps script library

醉酒当歌 提交于 2019-11-30 19:18:23

Until such functionality is natively supported by Google you can define empty functions with annotations on the same level as your constructor function. You can even keep your original code structure. This would enable auto-complete in the editor. Plus you'll get auto-generated documentation for your library, e.g. https://script.google.com/macros/library/versions/d/YOUR_PROJECT_KEY

Example:

/**
* Constructor.
* @constructor
* @param {String} apiKey Doxument API key
* @param {String} apiToken Doxument API token
*/    
function DoxumentApi(apiKey, apiToken) {
  // public api
  return {
        get: function(id, params) {
          var httpResponse = execute('/docs/' + id + '.json?' + buildQuery(params));
          return parse(httpResponse);
        }
    }
}

/**
* Get document record.
* @param {String} id document id
* @param {Object=} params optional. extra get params
* @return {Object} Document object
*/    
function get(id, params) {}

It doesn't work yet but the team does know about it. Until then you will need to document your libraries on a site. I guess you could also put the methods in the description. It really is a great start for the new service but I was with you about 5 minutes in and already wanting more. ;)

What about using OO?

It look very well organized and it's easy to document.

/**
 * A stopwatch Class.
 *
 * @constructor
 */
function Stopwatch() {
  this.current =  new Date().getTime();
}

/**
 * Starts the stopwatch
 */
Stopwatch.prototype.start = function(){
  this.current = new Date().getTime();
};

/**
 * Stops the stopwatch
 *
 * @return {number} Number of seconds since Stopwatch was started
 */
Stopwatch.prototype.stop = function(){
  return ((new Date().getTime()) - this.current) / 1000;
};

Example. In case your lib is imported as Utils.

var s = new Utils.Stopwatch();
s.start();

// (...) 

Logger.log(s.stop());

PS: This is untested code.

As a side effect you could have multiple Stopwatches, each one maintaining it's own local variable current

UPDATE

Although this is correctly documented following JSDoc it currently doesn't autocomplete the methods with Google Apps Script.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!