Skip to content

Instantly share code, notes, and snippets.

@thomaschaplin
Created November 11, 2021 10:30
Show Gist options
  • Select an option

  • Save thomaschaplin/7502ff1f972ebabd47b63739aa372321 to your computer and use it in GitHub Desktop.

Select an option

Save thomaschaplin/7502ff1f972ebabd47b63739aa372321 to your computer and use it in GitHub Desktop.
Pull Value Out Of Map
type itemMap<T> = {
[itemName: string]: T
}
type Environments = {
[x: string]: Environment
}
export enum Environment {
/* eslint-disable no-unused-vars */
STAGING = "staging",
FRONTEND_STAGING = "frontend-staging",
PRODUCTION = "production",
/* eslint-enable no-unused-vars */
}
export const pullValueOutOfMap = <T>(
map: itemMap<T>,
keyName: string,
errorMessage: string = ""
): T => {
const value = map[keyName]
if (!value) {
throw new Error(
`Test Error: We didn't expect "${keyName}" and didn't have it in our map. The properties our map has are:\n\n${Object.keys(
map
).join("\n")}${errorMessage ? `\n\n${errorMessage}\n\n` : ""}`
)
}
return value
}
export const environments: Environments = {
staging: Environment.STAGING,
"frontend-staging": Environment.FRONTEND_STAGING,
production: Environment.PRODUCTION,
}
const getEnvironment = (): Environment => {
const environment = process.env.ENVIRONMENT
return pullValueOutOfMap(
environments,
environment,
"You must set the environment in your .env file"
)
}
const environment = getEnvironment()
console.log(`Running tests in "${environment}" environment`)
/**
* ENVIRONMENT=staging node dist/u.js
* Running tests in "staging" environment
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment