Created
February 24, 2019 16:48
-
-
Save kn9ts/3458e32f2080b98003648bd6b0e8f5e7 to your computer and use it in GitHub Desktop.
Script to load up environment variables into the application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const yaml = require('js-yaml'); | |
const uuid = require('node-uuid'); | |
const appYamlConfigFile = 'app.yaml'; | |
const requiredEnvVariables = ['DATABASE_URL']; | |
// default configuration | |
process.env.API_VERSION = 1; | |
['SESSION_SECRET_KEY', 'WEB_TOKEN_SECRET'].forEach((configVar) => { | |
process.env[configVar] = uuid.v4(); | |
}); | |
// if an env has not been provided, default to development | |
if (!('NODE_ENV' in process.env)) process.env.NODE_ENV = 'development'; | |
if (process.env.NODE_ENV === 'development') { | |
const envKeys = Object.keys(process.env); | |
const allRequiredEnvVariablesExist = requiredEnvVariables.every( | |
(variable) => envKeys.indexOf(variable) !== -1 | |
); | |
// if the requiredEnvVariables have not been added | |
// maybe by GAE or Heroku ENV settings | |
if (!allRequiredEnvVariablesExist) { | |
if (fs.existsSync(appYamlConfigFile)) { | |
// Get the rest of the config from app.yaml config file | |
const appEnvConfigurations = yaml.safeLoad(fs.readFileSync(appYamlConfigFile, 'utf8')); | |
Object.keys(appEnvConfigurations).forEach((key) => { | |
process.env[key] = | |
typeof appEnvConfigurations[key] !== 'string' | |
? JSON.stringify(appEnvConfigurations[key]) | |
: appEnvConfigurations[key]; | |
}); | |
} else { | |
throw new Error(` | |
Missing app.yaml config file used while in development mode | |
It should have contents similar to the example below: | |
app.yaml | |
------------------------- | |
SECRET_CODE: '000000' | |
SECRET_KEY: 'a8eac82d7ac1461ba0348b0cb24d3f8140d3afb9be864e56a10d7e8026eaed66' | |
ENDPOINT: 'http://merchant-endpoint.com/mpesa/payment/complete' | |
DATABASE_URL: 'mongo+srv://eugene:password@localhost:27017' | |
------------------------- | |
`); | |
} | |
} | |
} |
Load it up in the index file of your nodejs, expressjs likely, application with require('./env')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now you can add all your env variables in an
app.yaml
in the same root folder as this: