config.ts•1.82 kB
import * as fs from 'fs';
import * as path from 'path';
import { DnsServerConfig } from '../types/dns';
export interface Config {
dns: DnsServerConfig;
cache?: {
enabled: boolean;
ttl: number;
maxSize: number;
};
logging?: {
level: 'debug' | 'info' | 'warn' | 'error';
file?: string;
};
}
export class ConfigManager {
private config: Config;
private configPath: string;
constructor(configPath?: string) {
this.configPath = configPath || path.join(process.cwd(), 'dns-config.json');
this.config = this.loadConfig();
}
private loadConfig(): Config {
try {
if (fs.existsSync(this.configPath)) {
const configData = fs.readFileSync(this.configPath, 'utf-8');
return JSON.parse(configData);
}
} catch (error) {
console.error('Failed to load config file, using defaults:', error);
}
return this.getDefaultConfig();
}
private getDefaultConfig(): Config {
return {
dns: {
servers: ['8.8.8.8', '8.8.4.4', '1.1.1.1', '1.0.0.1'],
timeout: 5000,
retries: 2,
useTCP: false
},
cache: {
enabled: true,
ttl: 300,
maxSize: 1000
},
logging: {
level: 'info'
}
};
}
getDnsConfig(): DnsServerConfig {
return this.config.dns;
}
getCacheConfig() {
return this.config.cache;
}
getLoggingConfig() {
return this.config.logging;
}
updateDnsServers(servers: string[]) {
this.config.dns.servers = servers;
this.saveConfig();
}
private saveConfig() {
try {
fs.writeFileSync(
this.configPath,
JSON.stringify(this.config, null, 2),
'utf-8'
);
} catch (error) {
console.error('Failed to save config:', error);
}
}
}