To Make Code Portable

We can create a constants library file like below and add internal ids in objects for different environments.

define(["n/runtime"],
    function (runtime) {
        // https://suiteanswers.custhelp.com/app/answers/detail/a_id/61225/loc/en_US
        // https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4296530806.html
        const DEPLOYMENT_ENVIRONMENT = runtime.accountId

        // these objects will contain the environment specific values we need
        const SB2 = {
            SHIP_METHOD: {
                "UPS Ground": 11
            }
        }

        const SB3 = {
            SHIP_METHOD: {
                "UPS Ground": 4
            }
        }
        
        // During feature development, when adding a new constant, add it to all environment objects.
        //
        // If the constant does not yet exist in the environment, set its value to null.
        //
        // In this way, we will maintain a set of constants for all environments, and we enable
        //   helpful errors as demonstrated below.
        const PRODUCTION = {
            SHIP_METHOD: {
                "UPS Ground": null
            }
        }

        // This is our dispatch object that references our above env specific objects. 
        //
        // It uses the account ID values as prop names.
        return CONSTANTS = {
            "37596_SB3": SB3,
            "37596_PRODUCTION": PRODUCTION
        }

        // At runtime when this lib file is loaded in a script, the code will dynamically return the correct
        //   environment object based on the account ID.
        if (DEPLOYMENT_ENVIRONMENT in CONSTANTS) {
            return CONSTANTS[DEPLOYMENT_ENVIRONMENT]
        } else {
            throw new Error("Constants not found for account: ", DEPLOYMENT_ENVIRONMENT)
        }
        
        // Throughout our scripts, all we have to do going forward is import this file and reference it like so:
        //     constants.SHIP_METHOD["UPS Ground"]
        // Or, better:
        //     constants.SHIP_METHOD.UPS_GROUND
        // We prefer the second method where possible because the IDE will warn us if we try to access an non-existant property
        //     constans.SHIP_METHOD.UPS_GROND >> IDE will highlight with a warning!
    });

Leave a comment

Your email address will not be published. Required fields are marked *