libflitter/utility/UtilityUnit.js

/**
 * @module libflitter/utility/UtilityUnit
 */

const Unit = require('../Unit')
const path = require('path')
const ServerDirective = require('../directives/ServerDirective')

/**
 * The utility unit contains various utility functions and tools that
 * are made available to almost all other units. Currently, a function
 * for restricting console.log calls by logging level is the one method
 * included. Also provides the path to the root folder of the app.
 * 
 * @extends module:libflitter/Unit~Unit
 */
class UtilityUnit extends Unit {

    /**
     * Loads the unit. Binds the application root and global logging function to the appropriate contexts.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app - the Flitter app
     * @param {module:libflitter/Context~Context} context - the unit's context
     * @returns {Promise<void>}
     */
    async go(app, context){
        
        context.bind('log', this.log)
        context.bind('approot', this.root())
        
        app.global.bind('log', this.log)
        app.global.bind('root', this.root())
        
    }

    /**
     * Prints a message to the console iff the logging level configured in "server.logging.level" is less than the specified message level.
     * This function is usually bound to the unit's context and the app's global context.
     * @param {string} message - the message to be printed
     * @param {Number} level - the level of the message to be printed
     * @param {boolean} [strict = false] - if true, print the message iff the message level is exactly equal to the configured logging level.
     */
    log(message, level=1, strict=false){
        const log_level = this.d.config.get('server.logging.level')
        
        if ( !strict && level <= log_level ){
            console.log(message)
        }
        else if ( strict && level == log_level ){
            console.log(message)
        }
    }

    /**
     * Get the fully-qualified path to the root folder of the Flitter application.
     * @returns {string}
     */
    root(){
        return path.dirname(require.main.filename || process.mainModule.filename || process.cwd())
    }

    /**
     * Get the name of this unit.
     * @returns {string} "utility"
     */
    name(){
        return "utility"
    }

    /**
     * Get the directives provided by this unit.
     * @returns {Object}
     */
    directives(){
        return {
            ServerDirective
        }
    }


    /**
     * Get the unit's migrations.
     * @returns {string}
     */
    migrations(){
        return path.resolve(__dirname, 'migrations')
    }
}

module.exports = UtilityUnit