Skip to content

Commit

Permalink
feat: #9
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexinhans committed Jan 20, 2024
1 parent 55336c5 commit 3fcfffb
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 19 deletions.
3 changes: 3 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NODE_ENV=development
NUMBER=0
BOOLEAN=true
4 changes: 3 additions & 1 deletion .env.development example
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
NODE_ENV=development
NODE_ENV=development
NUMBER=0
BOOLEAN=true
56 changes: 38 additions & 18 deletions src/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,51 @@ import { join } from 'node:path';
import { Logger } from 'tslog';
import { parseSync } from 'yargs';

export interface Env {
NODE_ENV: 'development' | 'production';
}
/**
* Typescript doesnt have support to get list of keys from an interface
*/
class EnvClass {
NODE_ENV!: 'development' | 'production';

BOOLEAN!: boolean;

NUMBER!: number;
}
export interface Env extends EnvClass {}
export type EnvKeys = keyof Env;
export type EnvKeysArray = Array<EnvKeys>;

const envLogger = new Logger({ type: 'pretty', name: 'Environment' });

// Function that retrieves the value of an environment variable
export function getEnv(name: EnvKeys, defaultValue = ''): string {
return process.env[name] || defaultValue;
function runChecks() {
const envClass = new EnvClass();
const keys: EnvKeysArray = Object.keys(envClass) as EnvKeysArray;
const undefinedKeys: string[] = [];

keys.forEach((key) => {
// TODO: check the types as well
const env = getEnv(key);

if (!env) {
undefinedKeys.push(key);
}
});

if (undefinedKeys.length > 0) {
throw new Error(
`[UNDEFINED_ENV_KEYS] Setup these env keys: ${undefinedKeys.join(', ')}`
);
}
}

// Function that retrieves the value of an environment variable as a boolean
export function getEnvAsBool(name: EnvKeys, defaultValue = false): boolean {
const value = getEnv(name);
return value === 'true' || value === '1'
? true
: value === 'false' || value === '0'
? false
: defaultValue;
export function isDeveloperMode(): boolean {
if (getEnv('NODE_ENV') === 'development') return true;
return false;
}

// Function that retrieves the value of an environment variable as a number
export function getEnvAsNumber(name: EnvKeys, defaultValue = 0): number {
const value = getEnv(name);
return Number.isNaN(Number(value)) ? defaultValue : Number(value);
// Function that retrieves the value of an environment variable
export function getEnv<T extends EnvKeys>(key: T): Env[T] {
return process.env[key] as Env[T];
}

// Function that loads the .env file from a specific location
Expand Down Expand Up @@ -62,3 +80,5 @@ process.argv.forEach((arg: string) => {
process.env[key] = value;
}
});

runChecks();

0 comments on commit 3fcfffb

Please sign in to comment.