import * as dotenv from 'dotenv'; dotenv.config({ quiet: true }); /** * Get the environmental string from .env. * Supports rewriting names to UPPER_SNAKE_CASE if isGlobal is set. * * @param {string} key The key * @param {boolean} [isGlobal=true] Indicates if global * @return {(string|undefined)} The environment string. */ export function getString( key: string, isGlobal: boolean = true ): string | undefined { let keyName: string = ''; if (isGlobal) { // Global values are DECLARED_LIKE_THIS=... for (let i: number = 0; i < key.length; i++) { if (key[i].toLowerCase() === key[i]) { // If is lowercase, skip. keyName += key[i]; } else { // If is uppercase, convert to snake case. keyName += `_${key[i].toLowerCase()}`; } } keyName = keyName.toUpperCase(); } else { // Non-global keys are parsed as passed keyName = key; } return process.env[keyName]; } /** * Get the environmental boolean from .env. * Supports rewriting names to UPPER_SNAKE_CASE if isGlobal is set. * * @param {string} key The key * @param {boolean} [isGlobal=true] Indicates if global * @return {(boolean|undefined)} The environment boolean. */ export function getBool( key: string, isGlobal: boolean = true ): boolean | undefined { const valueRead: string | undefined = getString(key, isGlobal); if (valueRead === undefined) return undefined; if (valueRead.toLowerCase() === 'true') return true; return false; } /** * Processes public url, returning protocol, fqdn and path. * proto://fqdn/path/ = fullPublicUrl * @return {RewriteStrings} The rewrite strings. */ export function getRewriteStrings(): RewriteStrings { const fullPublicUrl: string = getString('publicUrl', true)!; const url = new URL(fullPublicUrl); const proto = url.protocol.slice(0, -1); // https: -> https const fqdn = url.host; const path = url.pathname.replace(/\/+$/, '') + '/'; // /abc -> /abc/ const result: RewriteStrings = { fullPublicUrl, proto, fqdn, path }; return result; }; export type RewriteStrings = { fullPublicUrl: string; proto: string; fqdn: string; path: string; };