Skip to content

Instantly share code, notes, and snippets.

@pkellner
Created February 15, 2019 13:38
Show Gist options
  • Save pkellner/ac5cbe320d7d60a420fcd0f1c445aa52 to your computer and use it in GitHub Desktop.
Save pkellner/ac5cbe320d7d60a420fcd0f1c445aa52 to your computer and use it in GitHub Desktop.
import { RunTypes } from '../components/codecamp/common/CodeCampInterfaces';
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
/** A function that when called will return an environmental variable
* specified either in the .env file or the next.config.js defaults
* @param envKey value passed in which is environmental value without_DEV,_PROD or _STAGING
* @param devProdOrStaging
* @devProdOrStaging can only be "DEV","PROD", or "STAGING". If not included, then will default to process_env.NODE_ENV
* @returns returns the value after evaluating based on process.env.NODE_ENV
* */
const getEnvParameter = (envKey: string, devProdOrStaging?: RunTypes) => {
if (!devProdOrStaging) {
if (process.env.NODE_ENV === 'production') {
devProdOrStaging = 'PROD';
} else if (process.env.NODE_ENV === 'development') {
devProdOrStaging = 'DEV';
} else if (process.env.NODE_ENV === 'staging') {
devProdOrStaging = 'STAGING';
}
}
const baseUrl = `BASEURL_${devProdOrStaging}`;
let baseUrlValue = process.env[baseUrl];
if (!baseUrlValue) {
baseUrlValue = publicRuntimeConfig[`BASEURL_DEFAULT`];
}
if (!baseUrlValue) {
baseUrlValue = publicRuntimeConfig[`BASEURL_DEFAULT`];
}
const envKeyValue = `${envKey}_${devProdOrStaging}`;
const keyValue = process.env[envKeyValue];
const retVal = keyValue
? `${baseUrlValue}${keyValue}`
: baseUrlValue + publicRuntimeConfig[`${envKey}_DEFAULT`];
return retVal;
};
export default getEnvParameter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment