Search code examples
javascriptgoogle-apps-scriptwrapperencapsulation

Include GAS library as a source


I am trying to include the sources of BetterLog lib as a separate file, while keeping its referencing in the same as when added "as a library". How should I wrap it properly?

I've tried different approaches, but no luck. E.g.

BetterLog.gs:

BetterLog = () => { 
    // pasted lib src: https://github.com/peterherrmann/BetterLog/blob/master/Code.gs 
};

Code.gs:

Logger = BetterLog.useSpreadsheet(Settings.currentSpreadsheetID); 
// Calling it in the same way as calling lib-ed version
// However, when using sources, getting the error "BetterLog is null" 

Any suggestions?

EDIT: tricky part is that lib has some "public" methods, e.g.

function useSpreadsheet(optKey, optSheetName) {

while others are "private":

function hasAuth_() {

So the challenge is to do as small changes as possible in the lib sources.


Solution

  • When using BetterLog = () => { ... }, the code is not adequately wrapped because this statement is assigning a function.

    The simplest solution is to add the BetterLog code to a GS file, ensuring that you don't use the function and variable names in your code. Then, call the BetterLog functions without the BetterLog. prefix.

    If you still want to wrap the BetterLog code in a code block, then you might consider to use the namespace pattern:

    /**
     * Wrapper for BetterLog code by Peter Herrmann
     * @see {@link https://github.com/peterherrmann/BetterLog BetterLog}
     * @namespace
     */
    const BetterLog = (function(ns){ 
    // Add the BetterLog code here
    
    // Assign each public function to a ns property with the same name
    ns.useSpreadsheet = useSpreadsheet;
    ns.getLevel = getLevel;
    // Add here the other public functions that you want to expose
    
    // Before the closing of the Immediately-Invoked Function Expressions (IIFE), return the ns variable
    return ns;
    
    })({})
    

    Note: The JSDoc comment is not compulsory if your Apps Script project is private.