Skip to content

Commit

Permalink
feat: add getRequiredEnv
Browse files Browse the repository at this point in the history
  • Loading branch information
frytg committed Dec 17, 2024
1 parent bc2739b commit 35da008
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 4 deletions.
13 changes: 13 additions & 0 deletions check-required-env/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Check Required Env Changelog

## 2024-12-17 - 0.1.0

- feat: add `getRequiredEnv`

## 2024-11-27 - 0.0.1

- feat: add test for required env

## 2024-11-22 - 0.0.1

- feat: add check required env
4 changes: 2 additions & 2 deletions check-required-env/check-required-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import logger from '@frytg/logger'
/**
* Check if an environment variable is required and log an alert and exit if it is not set.
*
* @param name - The name of the environment variable.
* @returns void
* @param {string} name - The name of the environment variable.
* @returns {void}
*
* @example
* ```ts
Expand Down
7 changes: 5 additions & 2 deletions check-required-env/deno.jsonc
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
{
"$schema": "https://jsr.io/schema/config-file.v1.json",
"name": "@frytg/check-required-env",
"version": "0.0.1",
"exports": "./check-required-env.ts",
"version": "0.1.0",
"exports": {
".": "./check-required-env.ts",
"./get": "./get-required-env.ts"
},
"imports": {
"@frytg/logger": "jsr:@frytg/[email protected]"
}
Expand Down
34 changes: 34 additions & 0 deletions check-required-env/get-required-env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// load packages
import process from 'node:process'
import logger from '@frytg/logger'

/**
* Access an environment variable and log an alert and exit if it is not set.
*
* @param {string} name - The name of the environment variable.
* @param {boolean} preferThrowError - Whether to throw an error if the environment variable is not set.
* @returns {string} The value of the environment variable.
*
* @example
* ```ts
* import { getRequiredEnv } from '@frytg/check-required-env/get'
*
* getRequiredEnv('MY_IMPORTANT_ENV_VAR', false)
* ```
*/
export const getRequiredEnv = (name: string, preferThrowError = true): string => {
const value = process.env[name]

// return if the env variable is set
if (value !== undefined) return value

// log and exit if not set
logger.log({
level: 'alert',
message: `env ${name} is required`,
source: 'getRequiredEnv',
data: { name },
})
if (preferThrowError) throw new Error(`env ${name} is required`)
process.exit(1)
}

0 comments on commit 35da008

Please sign in to comment.