Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Documenting factories with JSDoc

In order to avoid using new in my JavaScript code, I write factories to create objects.

I have tried many combinations and the one that gives me the most satisfactory result is the following:

/**
 * Document module
 * @module app/document
 */
(function () {
    'use strict';

    /**
     * Factory that creates a document object.
     * @alias module:app/document.factory
     * @return {document}
     */
    function document() {
        /**
         * Get document id
         * @method id
         * @return {String}
         */
        var id = function id() {...},
            api = {
                id: id
            };

        return api;
    }

    /**
     * This module exports the {@link module:app/document.factory|factory} function.
     */
    module.exports = document;
}());

The problem with these comments is there is no document object defined. Therefore, I can't reference this object in another object and I can't inherit its documentation when I extends this object.

What is the appropriate way to document this kind of object?

If I use the @typedef tag, I get the static factory method and the document object properly documented but no id method documentation is generated by JSDoc:

/**
 * Document module.
 * @module app/document
 */
(function () {
    'use strict';

    /**
     * Factory that creates a document object.
     * @function module:app/document.factory
     * @return {document}
     */
    function factory(agent) {
        /**
         * @callback document~id
         * @returns {String}
         */
        var id = function id() {...},

            /**
             * @typedef document
             * @property {document~id} id
             */
            document = {
                id: id
            };

        return document;
    }

    module.exports = factory;
}());
like image 436
goriol Avatar asked Sep 13 '15 09:09

goriol


1 Answers

My recommendation to you is to well define the exports on your module using @typedef to define the type and then annotate the module.exports = factory with @type {FactoryDefinition}

 /** @typedef {{ id: !string }} */
 var DocumentDefinition;

 /** @typedef {!function(!object):!DocumentDefinition} */
 var FactoryDefinition;

/** @type {FactoryDefinition} */
module.exports = factory
like image 190
Sagi Avatar answered Sep 23 '22 04:09

Sagi