Search code examples
javascriptdesign-patternsarchitecturerevealing-module-pattern

JS Revealing module pattern: Params that shouldn't be used by usercode


I have a module written structured with the revealing module pattern. This contains a sub-module that kind of works as an overload. A few functions of the main module have parameters that shouldn't be used with usercode - only via the submodule. How can I access the params from the submodule but make them unavailable for "external usercode"? Should I make another layer for this?

var someNamespace = someNamespace || {};

someNamespace.someModule = (function () {

    // _customSiteUrl, _customToken shouldn't be available via usercode
    function create(listName, data, _customSiteUrl, _customToken) {
        ...
    }
    var XS = (function () {
        return {
            createXS: function (siteUrl, listName, data) {
                ...
                create(listName, data, siteUrl, token);
            }
        }
    })();

    return {
        create: create,
        XS: XS,
        ...
    }
})();

someNamespace.someModule.create("hi", {}, "https://...", "someHash"); //Should not be possible!!
someNamespace.someModule.create("hi", {}); //Should be used

Solution

  • You can just add another "layer" in your .someModulewith the any user-inaccessible variables being declared locally, and change the create: property of your return to this layer, instead of the base function.

    You have to remember, you can create as many "overloads" as you like, but they will all retain the same parameters that you declare in the "overload" you're returning. What you pass inside that overload to the base function (create) is entirely up to you and entirely private.

    someNamespace.someModule = (function () {
    
        // _customSiteUrl, _customToken shouldn't be available via usercode
        function create(listName, data, _customSiteUrl, _customToken) {
            ...
        }
    
        function userAccessibleCreate () {
            return create(parameters, you, want);
        };
        var XS = (function () {
            return {
                createXS: function (siteUrl, listName, data) {
                    ...
                    create(listName, data, siteUrl, token);
                }
            }
        })();
    
        return {
            create: userAccessibleCreate,
            XS: XS,
            ...
        }
    })();
    

    Now, the user can only only do someNamespace.someModule.create("hi", {});.