UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

170 lines (169 loc) 6.3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.initialize = initialize; exports.getConfig = getConfig; exports.getEventSubscription = getEventSubscription; exports.checkRequiredEnv = checkRequiredEnv; exports.ensureAuditInitialized = ensureAuditInitialized; exports.getPostgresDbUri = getPostgresDbUri; exports.getMongoUri = getMongoUri; exports.getRedisDbHostAndPort = getRedisDbHostAndPort; exports.shutdown = shutdown; const dt_audit_library_1 = require("dt-audit-library"); const db_1 = require("../db/db"); const dotenv_1 = __importDefault(require("dotenv")); const events_1 = require("../events"); const http_utils_1 = require("../utils/http.utils"); dotenv_1.default.config(); let config = null; let auditInitialized = false; let eventSubscription = null; async function initialize(cfg) { // Initialize config config = { ...cfg }; // Validate service URLs if provided if (cfg.DEVICE_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.DEVICE_SERVICE)) { throw new Error(`Invalid DEVICE_SERVICE URL: ${cfg.DEVICE_SERVICE}`); } if (cfg.ADMIN_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ADMIN_SERVICE)) { throw new Error(`Invalid ADMIN_SERVICE URL: ${cfg.ADMIN_SERVICE}`); } if (cfg.ACCESS_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ACCESS_SERVICE)) { throw new Error(`Invalid ACCESS_SERVICE URL: ${cfg.ACCESS_SERVICE}`); } if (cfg.ENERGY_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ENERGY_SERVICE)) { throw new Error(`Invalid ENERGY_SERVICE URL: ${cfg.ENERGY_SERVICE}`); } // Initialize internal event subscription if handler is provided if (cfg.INTERNAL_EVENT_HANDLER) { try { eventSubscription = new events_1.InternalEventSubscription(cfg.INTERNAL_EVENT_HANDLER); cfg.LOGGER.info("InternalEventSubscription initialized successfully"); } catch (error) { cfg.LOGGER.error("Failed to initialize InternalEventSubscription", { error, }); throw error; } } // Connect to databases try { await (0, db_1.connectDatabase)(); cfg.LOGGER.info("Database connections established successfully"); } catch (error) { cfg.LOGGER.error("Failed to connect to databases", { error }); throw error; } // Subscribe to events if event subscription is available if (eventSubscription) { try { await eventSubscription.subscribe(); cfg.LOGGER.info("Event subscription started successfully"); } catch (error) { cfg.LOGGER.error(`Failed to start event subscription: ${error.message || error.toString()}`); // Don't throw here as the main setup should continue } } // Check if required env variables are set checkRequiredEnv(); // Initialize audit ensureAuditInitialized(); console.log("dt-common-device: Initialization completed successfully"); } function getConfig() { if (!config) { throw new Error("dt-common-device: Library not initialized. Call initialize() first."); } return config; } function getEventSubscription() { return eventSubscription; } function checkRequiredEnv() { const requiredEnv = [ "AWS_SECRET_ACCESS_KEY", "AWS_REGION", "AWS_ACCESS_KEY_ID", "EVENT_BUS_NAME", "ADMIN_DB_URI", "MONGODB_URI", "REDIS_HOST", "REDIS_PORT", "POSTHOG_API_KEY", "POSTHOG_HOST", ]; const missing = requiredEnv.filter((key) => !process.env[key]); if (missing.length > 0) { throw new Error(`Missing required AWS environment variables for dt-pub-sub: ${missing.join(", ")}`); } } function ensureAuditInitialized() { if (auditInitialized) return; const apiKey = process.env.POSTHOG_API_KEY; const host = process.env.POSTHOG_HOST; if (!apiKey || !host) { getConfig().LOGGER.error("POSTHOG_API_KEY and POSTHOG_HOST must be set in environment variables"); throw new Error("dt-common-device: POSTHOG_API_KEY and POSTHOG_HOST must be set in environment variables"); } (0, dt_audit_library_1.initializeAudit)(apiKey, host); auditInitialized = true; } // // Direct logger export for easier usage // export function getLogger(): ILogger { // return getConfig().LOGGER; // } /** * Returns the PostgreSQL DB URI from environment variables. * Throws an error if not set. */ function getPostgresDbUri() { const fullUri = process.env.ADMIN_DB_URI; if (!fullUri) { getConfig().LOGGER.error("ADMIN_DB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: ADMIN_DB_URI must be set in environment variables or .env file"); } return fullUri; } function getMongoUri() { const fullUri = process.env.MONGODB_URI; if (!fullUri) { getConfig().LOGGER.error("MONGODB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: MONGODB_URI must be set in environment variables or .env file"); } return fullUri; } /** * Returns the Redis DB Host and port from environment variables. * Throws an error if not set. */ function getRedisDbHostAndPort() { const host = process.env.REDIS_HOST; const port = process.env.REDIS_PORT; if (!host || !port) { getConfig().LOGGER.error("REDIS_HOST and REDIS_PORT must be set in environment variables"); throw new Error("dt-common-device: REDIS_HOST and REDIS_PORT must be set in environment variables"); } return { host, port: Number(port) }; } /** * Graceful shutdown function */ async function shutdown() { if (eventSubscription) { try { await eventSubscription.unsubscribe(); getConfig().LOGGER.info("Event subscription stopped successfully"); } catch (error) { getConfig().LOGGER.error("Failed to stop event subscription", { error }); } } getConfig().LOGGER.info("dt-common-device: Shutdown completed"); }