UNPKG

status-checker

Version:

A lean, dependency-free URL status checker library

95 lines 3.41 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigLoader = void 0; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const logger_1 = require("./logger"); /** * Configuration loader and validator */ class ConfigLoader { /** * Create a new ConfigLoader * @param logger Logger instance */ constructor(logger) { this.logger = logger || new logger_1.Logger('info'); } /** * Load configuration from a file * @param filePath Path to the configuration file * @returns Parsed configuration */ loadConfig(filePath) { try { // Resolve path const resolvedPath = path_1.default.resolve(filePath); this.logger.debug(`Loading configuration from ${resolvedPath}`); // Check if file exists if (!fs_1.default.existsSync(resolvedPath)) { throw new Error(`Configuration file not found: ${resolvedPath}`); } // Read and parse file const fileContent = fs_1.default.readFileSync(resolvedPath, 'utf-8'); const config = JSON.parse(fileContent); // Validate configuration this.validateConfig(config); this.logger.info(`Successfully loaded configuration with ${config.urls.length} URLs`); return config; } catch (error) { const message = error instanceof Error ? error.message : String(error); this.logger.error(`Failed to load configuration: ${message}`); throw error; } } /** * Validate the configuration * @param config Configuration to validate */ validateConfig(config) { // Check if URLs array exists if (!config.urls || !Array.isArray(config.urls)) { throw new Error('Configuration must contain a "urls" array'); } // Check if URLs array is not empty if (config.urls.length === 0) { throw new Error('Configuration must contain at least one URL'); } // Validate each URL config.urls.forEach((urlConfig, index) => { this.validateUrlConfig(urlConfig, index); }); // Set default values config.globalTimeout = config.globalTimeout || 5000; config.globalSuccessCodes = config.globalSuccessCodes || [200]; config.logLevel = config.logLevel || 'info'; } /** * Validate a URL configuration * @param urlConfig URL configuration to validate * @param index Index of the URL in the configuration */ validateUrlConfig(urlConfig, index) { // Check if URL exists if (!urlConfig.url) { throw new Error(`URL at index ${index} is missing the "url" property`); } // Check if URL is valid try { new URL(urlConfig.url); } catch (error) { throw new Error(`URL at index ${index} is invalid: ${urlConfig.url}`); } // Set default name if not provided if (!urlConfig.name) { urlConfig.name = `URL ${index + 1}`; } } } exports.ConfigLoader = ConfigLoader; //# sourceMappingURL=config.js.map