Skip to content
This repository has been archived by the owner on Aug 11, 2024. It is now read-only.

Commit

Permalink
Merge pull request #272 from beabee-communityrm/feat/better-env-asser…
Browse files Browse the repository at this point in the history
…t-messages

feat: add useful messages to config checks
  • Loading branch information
wpf500 authored Jun 21, 2023
2 parents 63cd228 + 91f21f3 commit 0b3ac03
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,23 @@ import { strict as assert } from "assert";

export function s(name: string, def?: string): string {
const value = process.env[name] || def;
assert(value !== undefined);
assert(value !== undefined, `Missing environment variable ${name}`);
return value;
}

export function ss(name: string, def?: string[]): string[] {
const value = process.env[name]?.split(",") || def;
assert(value !== undefined);
assert(value !== undefined, `Missing environment variable ${name}`);
return value;
}

export function n(name: string, def?: number): number {
const value = Number(process.env[name]) || def;
assert(value !== undefined && !isNaN(value));
assert(value !== undefined, `Missing environment variable ${name}`);
assert(
!isNaN(value),
`Invalid number for environment variable ${name}: ${process.env[name]}`
);
return value;
}

Expand All @@ -23,7 +27,10 @@ export function b(name: string, def?: boolean): boolean {
if (value === undefined && def !== undefined) {
return def;
}
assert(value === "true" || value === "false");
assert(
value === "true" || value === "false",
`Invalid boolean for environment variable ${name}: ${value}`
);
return value === "true";
}

Expand All @@ -33,12 +40,20 @@ export function e<T extends readonly string[]>(
def?: typeof options[number]
): typeof options[number] {
const value = s(name, def);
assert(options.indexOf(value) !== -1);
assert(
options.indexOf(value) !== -1,
`Invalid value for environment variable ${name}: ${value}. Valid options are: ${options.join(
", "
)}`
);
return value;
}

export function json(name: string, def?: any): any {
const value = process.env[name];
assert(value !== undefined || def !== undefined);
assert(
value !== undefined || def !== undefined,
`Missing environment variable ${name}`
);
return value === undefined ? def : JSON.parse(value);
}

0 comments on commit 0b3ac03

Please sign in to comment.