Files
kittyBE/src/tools/env.ts
sherl d7f4006698
All checks were successful
Build and push Docker image / build (push) Successful in 2m50s
Release new version / release (push) Successful in 26s
Update changelog / changelog (push) Successful in 25s
feat: add link creation and lookup
finally has the bare minimum functionality to say that it works!
2026-01-03 10:51:59 +01:00

88 lines
2.2 KiB
TypeScript

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;
};