@bernierllc/connection-parser
v1.0.6
Published
Universal connection string parsing and configuration management for databases, APIs, and services
Readme
@bernierllc/connection-parser
Universal connection string parsing and configuration management for databases, APIs, and services.
Installation
npm install @bernierllc/connection-parserUsage
import { parseConnection, parseDatabaseURL, redactCredentials } from '@bernierllc/connection-parser';
// Parse any connection string
const result = parseConnection('postgresql://user:pass@localhost:5432/mydb?ssl=true&pool_max=20');
console.log(result.config);
// {
// protocol: 'postgresql',
// host: 'localhost',
// port: 5432,
// database: 'mydb',
// username: 'user',
// password: 'pass',
// ssl: true,
// pooling: { max: 20 }
// }
// Parse database-specific URLs
const dbResult = parseDatabaseURL('mysql://root:secret@localhost:3306/testdb');
// Safely redact credentials for logging
const safeUrl = redactCredentials('postgresql://user:secret@localhost:5432/mydb');
console.log(safeUrl); // postgresql://****:****@localhost:5432/mydbFeatures
- Universal Parsing: Supports databases (PostgreSQL, MySQL, MongoDB, Redis), APIs (HTTP/HTTPS, WebSocket, GraphQL), and services (AMQP, Kafka, NATS, MQTT, LDAP)
- Credential Security: Safe credential extraction and redaction for logging
- Connection Pooling: Automatic extraction of pooling configuration from query parameters
- Validation: Comprehensive validation of connection formats and parameters
- Normalization: Consistent formatting and default value assignment
- Type Safety: Full TypeScript support with strict typing
- Performance: Optimized for high-throughput parsing (>10,000 connections/second)
- NeverHub Integration: Optional integration with NeverHub service discovery
API Reference
Core Functions
parseConnection(connectionString, options?)
Parses any connection string and routes to the appropriate parser based on protocol.
const result = parseConnection('postgresql://localhost:5432/mydb', {
validateFormat: true,
extractCredentials: true,
parsePooling: true
});
console.log(result.valid); // true
console.log(result.metadata.type); // 'database'parseDatabaseURL(url, options?)
Specialized parser for database connection strings.
const result = parseDatabaseURL('postgresql://user:pass@localhost:5432/mydb?pool_min=5&pool_max=20');
console.log(result.config.pooling); // { min: 5, max: 20 }
console.log(result.metadata.hasPooling); // trueparseAPIEndpoint(endpoint, options?)
Specialized parser for API endpoints.
const result = parseAPIEndpoint('https://api.example.com/v1/users?timeout=30000');
console.log(result.config.path); // '/v1/users'
console.log(result.config.options.timeout); // 30000parseServiceURL(url, options?)
Specialized parser for service URLs (message queues, directory services).
const result = parseServiceURL('amqp://guest:guest@localhost:5672/vhost?heartbeat=30');
console.log(result.config.database); // 'vhost' (virtual host)
console.log(result.config.options.heartbeat); // 30Utility Functions
validateConnection(config)
Validates a connection configuration object.
import { validateConnection } from '@bernierllc/connection-parser';
const result = validateConnection({
protocol: 'postgresql',
host: 'localhost',
port: 5432,
database: 'mydb'
});
console.log(result.valid); // true
console.log(result.errors); // []normalizeConnection(config)
Normalizes a connection configuration to standard format.
import { normalizeConnection } from '@bernierllc/connection-parser';
const normalized = normalizeConnection({
protocol: 'PostgreSQL:', // Will be normalized to 'postgresql'
host: 'MyHost.Example.Com', // Will be normalized to 'myhost.example.com'
database: ' mydb ' // Will be trimmed to 'mydb'
});buildConnectionString(config)
Builds a connection string from a configuration object.
import { buildConnectionString } from '@bernierllc/connection-parser';
const connectionString = buildConnectionString({
protocol: 'postgresql',
username: 'user',
password: 'pass',
host: 'localhost',
port: 5432,
database: 'mydb',
ssl: true,
pooling: { min: 5, max: 20 }
});
// Result: postgresql://user:pass@localhost:5432/mydb?ssl=true&pool_min=5&pool_max=20redactCredentials(connectionString)
Safely redacts credentials from connection strings for logging.
import { redactCredentials } from '@bernierllc/connection-parser';
const safe = redactCredentials('postgresql://user:secret@localhost:5432/mydb');
console.log(safe); // postgresql://****:****@localhost:5432/mydbParse Options
interface ParseOptions {
validateFormat?: boolean; // Validate connection format (default: true)
extractCredentials?: boolean; // Extract username/password (default: true)
normalizePort?: boolean; // Set default ports (default: true)
parsePooling?: boolean; // Extract pooling config (default: true)
redactSecrets?: boolean; // Redact credentials in raw field (default: false)
allowedProtocols?: string[]; // Restrict allowed protocols
}Connection Types
Database Connections
PostgreSQL
const result = parseDatabaseURL('postgresql://user:pass@localhost:5432/mydb?ssl=true');
const result2 = parseDatabaseURL('postgres://user:pass@localhost/mydb'); // Alternative formatMySQL
const result = parseDatabaseURL('mysql://root:password@localhost:3306/database?charset=utf8mb4');MongoDB
const result = parseDatabaseURL('mongodb://user:pass@localhost:27017/mydb?authSource=admin');
const result2 = parseDatabaseURL('mongo://localhost/mydb'); // Alternative formatRedis
const result = parseDatabaseURL('redis://localhost:6379/0');
const result2 = parseDatabaseURL('rediss://localhost:6380/1'); // SSL RedisAPI Endpoints
REST APIs
const result = parseAPIEndpoint('https://api.example.com/v1/users?timeout=30000');GraphQL
const result = parseAPIEndpoint('https://api.example.com/graphql');WebSockets
const result = parseAPIEndpoint('wss://ws.example.com/socket');Service Connections
AMQP/RabbitMQ
const result = parseServiceURL('amqp://guest:guest@localhost:5672/vhost');
const result2 = parseServiceURL('amqps://user:[email protected]:5671/'); // SSL AMQPApache Kafka
const result = parseServiceURL('kafka://localhost:9092/mytopic?group_id=consumer1');NATS
const result = parseServiceURL('nats://nats.example.com:4222?subject=events');MQTT
const result = parseServiceURL('mqtt://localhost:1883?client_id=client1&qos=1');
const result2 = parseServiceURL('mqtts://mqtt.example.com:8883'); // SSL MQTTLDAP
const result = parseServiceURL('ldap://ldap.example.com:389/dc=example,dc=com');
const result2 = parseServiceURL('ldaps://ldap.example.com:636/dc=example,dc=com'); // SSL LDAPEnvironment Variables
Parse connection strings from environment variables:
import { parseConnection } from '@bernierllc/connection-parser';
const dbConfig = parseConnection(process.env.DATABASE_URL || '', {
validateFormat: true,
parsePooling: true
});
if (!dbConfig.valid) {
throw new Error(`Invalid database URL: ${dbConfig.errors?.join(', ')}`);
}
// Use dbConfig.config for database connectionConnection Pooling
Extract pooling configuration from query parameters:
const result = parseConnection('postgresql://localhost/db?pool_min=5&pool_max=20&pool_timeout=30000');
console.log(result.config.pooling);
// {
// min: 5,
// max: 20,
// timeout: 30000
// }
// Alternative parameter names are supported
const result2 = parseConnection('mysql://localhost/db?minConnections=2&maxConnections=10');
console.log(result2.config.pooling); // { min: 2, max: 10 }Security Features
Credential Redaction
import { redactCredentials, parseConnection } from '@bernierllc/connection-parser';
const connectionString = 'postgresql://admin:topsecret@localhost:5432/mydb';
// Safe for logging
console.log(redactCredentials(connectionString));
// Output: postgresql://****:****@localhost:5432/mydb
// Parse without extracting credentials
const result = parseConnection(connectionString, { extractCredentials: false });
console.log(result.config.username); // undefined
console.log(result.config.password); // undefinedProtocol Validation
const result = parseConnection('postgresql://localhost/db', {
allowedProtocols: ['postgresql', 'mysql'] // Restrict allowed protocols
});Error Handling
import { parseConnection, ConnectionParserError } from '@bernierllc/connection-parser';
try {
const result = parseConnection('invalid-url');
if (!result.valid) {
console.error('Parsing errors:', result.errors);
}
} catch (error) {
if (error instanceof ConnectionParserError) {
console.error('Parser error:', error.message);
console.error('Error code:', error.code);
console.error('Protocol:', error.protocol);
}
}NeverHub Integration
When NeverHub is available, the package automatically integrates for service discovery and telemetry:
import { initializeNeverHubIntegration } from '@bernierllc/connection-parser';
// Initialize NeverHub integration (optional)
const isIntegrated = await initializeNeverHubIntegration();
if (isIntegrated) {
console.log('NeverHub integration active');
// Parsing events will be automatically published to NeverHub
const result = parseConnection('postgresql://localhost/db');
// Event 'config.connection.parsed' published to NeverHub
}Performance
The parser is optimized for high-throughput scenarios:
- >10,000 connections/second parsing performance
- Minimal memory allocation during parsing
- Efficient validation with early returns
- Zero external dependencies (only Node.js built-ins)
// Benchmark example
const startTime = process.hrtime.bigint();
for (let i = 0; i < 10000; i++) {
parseConnection('postgresql://user:pass@localhost:5432/mydb');
}
const endTime = process.hrtime.bigint();
const durationMs = Number(endTime - startTime) / 1_000_000;
console.log(`Parsed 10,000 connections in ${durationMs}ms`);Type Definitions
interface ConnectionConfig {
protocol: string;
host: string;
port?: number;
database?: string;
username?: string;
password?: string;
path?: string;
query?: Record<string, string>;
ssl?: boolean;
pooling?: {
min?: number;
max?: number;
timeout?: number;
idle?: number;
};
options?: Record<string, unknown>;
}
interface ParseResult {
config: ConnectionConfig;
raw: string;
valid: boolean;
errors?: string[];
metadata: {
type: 'database' | 'api' | 'service' | 'generic';
hasCredentials: boolean;
hasPooling: boolean;
isSecure: boolean;
};
}See Also
- @bernierllc/neverhub-adapter - Service discovery and event bus integration
- @bernierllc/logger - Structured logging with connection parsing integration
License
Copyright (c) 2025 Bernier LLC. All rights reserved.
