UNPKG

@linkedmink/node-route53-dynamic-dns

Version:

Background process that updates AWS Route 53 DNS address records whenever the public IP of the hosting environment changes

97 lines 3.22 kB
import dotenv from "dotenv"; import fs from "node:fs/promises"; import { configDefaultMap, IS_CONTAINERIZED_ENV_VAR, NodeEnv, } from "../constants/config.mjs"; export class ConfigError extends Error { } /** * Cache shared app configuration from files in memory */ export class EnvironmentConfig { fileBuffers = new Map(); jsonData = new Map(); environment; constructor(dotEnvPath = ".env") { dotenv.config({ path: dotEnvPath, override: true }); this.environment = (process.env.NODE_ENV?.toLowerCase() ?? NodeEnv.Production); } get isEnvironmentLocal() { return this.environment === NodeEnv.Local; } get isEnvironmentProd() { return this.environment === NodeEnv.Production; } get isEnvironmentContainerized() { return process.env[IS_CONTAINERIZED_ENV_VAR]?.trim().toLowerCase() === "true"; } getString = (key) => { return this.getConfigValue(key); }; getStringOrNull = (key) => { return this.getConfigValueOrNull(key); }; getNumber = (key) => { const value = this.getConfigValue(key); return this.parseNumberOrThrow(key, value); }; getNumberOrNull = (key) => { const value = this.getConfigValueOrNull(key); return value !== null ? this.parseNumberOrThrow(key, value) : null; }; getBool = (key) => { const value = this.getConfigValue(key); return this.parseBooleanOrThrow(key, value); }; // prettier-ignore getJson = (key) => { const json = this.jsonData.get(key); if (json) { return json; } const value = this.getConfigValue(key); const parsed = JSON.parse(value); this.jsonData.set(key, parsed); return parsed; }; getFileBuffer = async (key) => { const buffer = this.fileBuffers.get(key); if (buffer) { return buffer; } const filePath = this.getConfigValue(key); const data = await fs.readFile(filePath); this.fileBuffers.set(key, data); return data; }; getConfigValue = (key) => { const configValue = process.env[key] || configDefaultMap.get(key); if (configValue) { return configValue; } throw new ConfigError(`Environmental variable must be defined: ${key}`); }; getConfigValueOrNull = (key) => { const configValue = typeof process.env[key] === "string" ? process.env[key] : configDefaultMap.get(key); if (configValue) { return configValue; } return null; }; parseNumberOrThrow = (key, value) => { const number = Number(value); if (isNaN(number)) { throw new ConfigError(`Config value is not a number: ${key}=${value}`); } return number; }; parseBooleanOrThrow = (key, value) => { const stringValue = value.toLowerCase(); if (stringValue === "true") { return true; } if (stringValue === "false") { return false; } throw new ConfigError(`Config value is not a boolean: ${key}=${value}`); }; } //# sourceMappingURL=environment-config.mjs.map