libflitter/services/ServicesUnit.js

/**
 * @module libflitter/services/ServicesUnit
 */

const CanonicalUnit = require('../canon/CanonicalUnit')
const error_context = require('../errors/error_context.fn')

/**
 * Unit to load and manage externally-defined services.
 * @extends module:libflitter/canon/CanonicalUnit~CanonicalUnit
 */
class ServicesUnit extends CanonicalUnit {
    /**
     * Get the name of the service provided by this unit: 'services'
     * @returns {string} - 'services'
     */
    static get name() {
        return 'services'
    }

    /**
     * Instantiate the unit.
     * @param {string} [base_directory = './app/services']
     */
    constructor(base_directory = './app/services') {
        super(base_directory)

        /**
         * The canonical name of the item.
         * @type {string} = 'service'
         */
        this.canonical_item = 'service'

        /**
         * The file extension of the canonical item files.
         * @type {string} - '.service.js'
         */
        this.suffix = '.service.js'
    }

    /**
     * Prepare a single canonical service and return the value that should be given by the resolver.
     * The services are registered into the dependency injector by their canonical name.
     * @param {object} info
     * @param {module:libflitter/app/FlitterApp} info.app
     * @param {string} info.name - the unqualified canonical name
     * @param {*} info.instance - the static service CLASS from the file
     * @returns {Promise<*>}
     */
    async init_canonical_file({app, name, instance}) {
        try {
            await this.app.di().container.register_service(name, instance)
            return instance
        } catch (e) {
            throw error_context(e, {
                file_name: name,
            })
        }
    }

    /**
     * Get the templates provided by this unit: 'service'
     * @returns {object}
     */
    templates() {
        return {
            service: {
                template: require('../templates/service'),
                directory: this.directory,
                extension: this.suffix,
            }
        }
    }
}

module.exports = exports = ServicesUnit