Skip to content

x0VIER/typescript-config-manager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

TypeScript Configuration Manager

TypeScript Node.js License

A type-safe, feature-rich configuration management system for modern Node.js and TypeScript applications. Manage your app settings with confidence using strong typing and validation.

Features

  • 🔒 Type-Safe: Full TypeScript support with type inference
  • 📁 Multiple Formats: Support for JSON and .env files
  • 🔍 Deep Access: Get/set nested configuration values with dot notation
  • 👀 Watchers: React to configuration changes in real-time
  • 🔀 Merging: Merge configurations from multiple sources
  • ✅ Validation: Schema-based configuration validation
  • 💾 Auto-Save: Persist changes automatically or on-demand
  • 📤 Export: Convert between JSON and .env formats
  • 🎯 Default Values: Automatic default configuration generation

Installation

# Clone the repository
git clone https://github.com/x0VIER/typescript-config-manager.git
cd typescript-config-manager

# Install dependencies
npm install

# Build the project
npm run build

Usage

Programmatic API

import ConfigManager from './config-manager';

// Create config manager instance
const config = new ConfigManager({
    filePath: './config.json',
    format: 'json',
    createIfMissing: true
});

// Get configuration values
const appName = config.get<string>('app.name');
const port = config.get<number>('server.port', 3000);

// Set configuration values
config.set('server.port', 8080);
config.set('database.host', 'localhost');

// Save changes
config.save();

// Watch for changes
config.watch('server.port', (newPort) => {
    console.log(`Port changed to: ${newPort}`);
});

// Check if key exists
if (config.has('database.password')) {
    // Do something
}

// Delete a key
config.delete('temp.data');

// Merge configurations
config.merge({
    features: {
        auth: true,
        api: true
    }
});

// Export to different format
config.export('.env', 'env');

// Print all configuration
config.print();

Command Line Interface

# Get a value
ts-node config-manager.ts get app.name --config config.json

# Set a value
ts-node config-manager.ts set server.port 8080 --config config.json

# Delete a key
ts-node config-manager.ts delete temp.data --config config.json

# List all configuration
ts-node config-manager.ts list --config config.json

# Export to .env format
ts-node config-manager.ts export .env env --config config.json

# Validate configuration
ts-node config-manager.ts validate --config config.json

Configuration Formats

JSON Format

{
  "app": {
    "name": "MyApp",
    "version": "1.0.0",
    "environment": "development"
  },
  "server": {
    "host": "localhost",
    "port": 3000
  },
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "mydb"
  }
}

ENV Format

APP_NAME=MyApp
APP_VERSION=1.0.0
APP_ENVIRONMENT=development
SERVER_HOST=localhost
SERVER_PORT=3000
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=mydb

API Reference

Constructor Options

Option Type Description Default
filePath string Path to configuration file Required
format 'json' | 'env' Configuration format 'json'
createIfMissing boolean Create default config if missing false
validate boolean Enable validation false

Methods

get<T>(keyPath: string, defaultValue?: T): T

Get configuration value by dot-notation path.

const port = config.get<number>('server.port', 3000);

set(keyPath: string, value: any): void

Set configuration value by dot-notation path.

config.set('database.host', 'db.example.com');

has(keyPath: string): boolean

Check if configuration key exists.

if (config.has('features.auth')) {
    // Feature is configured
}

delete(keyPath: string): boolean

Delete configuration key.

config.delete('temp.cache');

getAll(): ConfigSchema

Get entire configuration object.

const allConfig = config.getAll();

save(): void

Save configuration to file.

config.save();

watch(keyPath: string, callback: (value: any) => void): void

Watch for changes to a specific key.

config.watch('server.port', (port) => {
    console.log(`Server port changed to: ${port}`);
});

merge(otherConfig: ConfigSchema): void

Merge another configuration object.

config.merge({ newFeature: { enabled: true } });

export(outputPath: string, format: 'json' | 'env'): void

Export configuration to different format.

config.export('.env.production', 'env');

validate(schema: ConfigSchema): boolean

Validate configuration against schema.

const isValid = config.validate({
    app: { name: 'string' },
    server: { port: 'number' }
});

print(): void

Print configuration to console.

config.print();

Use Cases

  • Application Settings: Manage app configuration across environments
  • Feature Flags: Toggle features with configuration
  • Database Connections: Store connection strings and credentials
  • API Configuration: Manage API endpoints and keys
  • Multi-Environment: Different configs for dev, staging, production
  • Microservices: Centralized configuration management

Examples

Environment-Specific Configuration

const env = process.env.NODE_ENV || 'development';
const config = new ConfigManager({
    filePath: `./config.${env}.json`,
    format: 'json',
    createIfMissing: true
});

Configuration with Validation

const config = new ConfigManager({
    filePath: './config.json',
    format: 'json'
});

const schema = {
    'app.name': true,
    'server.port': true,
    'database.host': true
};

if (!config.validate(schema)) {
    throw new Error('Invalid configuration');
}

Hot Reload Configuration

config.watch('features.newFeature', (enabled) => {
    if (enabled) {
        console.log('New feature enabled!');
        // Initialize new feature
    }
});

Requirements

  • Node.js 16.0.0 or higher
  • TypeScript 5.0.0 or higher

Contributing

Contributions are welcome! Please feel free to submit pull requests, report bugs, or suggest features.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Created by x0VIER - TypeScript & Node.js Tools

Roadmap

  • Add YAML format support
  • Implement configuration encryption
  • Add remote configuration loading (HTTP/S3)
  • Create web-based configuration editor
  • Add configuration versioning
  • Implement configuration diffing
  • Add support for configuration templates
  • Create VS Code extension

Alternatives

For more advanced features, consider:

  • dotenv: Simple .env file loading
  • config: Hierarchical configurations
  • convict: Schema-based configuration
  • nconf: Hierarchical configuration with multiple sources

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published