import fs from 'fs';
import path from 'path';
import { ServerConfig } from '../types';
/**
* Service for managing server configuration
*/
export class ConfigService {
private config: ServerConfig;
/**
* Default configuration values
*/
private readonly defaultConfig: ServerConfig = {
port: 3000,
contextPath: path.join(process.cwd(), 'context.json'),
autoInject: true,
triggerKeywords: ['new project', 'build', 'create', 'develop']
};
/**
* Initialize the configuration service
* @param configPath - Path to the configuration file
*/
constructor(private configPath: string = path.join(process.cwd(), 'config.json')) {
this.config = this.loadConfig();
}
/**
* Load configuration from file or use defaults
* @returns The loaded configuration
*/
private loadConfig(): ServerConfig {
try {
if (fs.existsSync(this.configPath)) {
const fileContent = fs.readFileSync(this.configPath, 'utf8');
const loadedConfig = JSON.parse(fileContent) as Partial<ServerConfig>;
// Merge with default config to ensure all properties exist
return { ...this.defaultConfig, ...loadedConfig };
}
// If file doesn't exist, return default config
return this.defaultConfig;
} catch (error) {
console.error('Error loading config:', error instanceof Error ? error.message : String(error));
return this.defaultConfig;
}
}
/**
* Get the current configuration
* @returns The current server configuration
*/
public getConfig(): ServerConfig {
return { ...this.config };
}
/**
* Update the configuration
* @param newConfig - New configuration values
* @returns The updated configuration
*/
public updateConfig(newConfig: Partial<ServerConfig>): ServerConfig {
this.config = { ...this.config, ...newConfig };
this.saveConfig();
return { ...this.config };
}
/**
* Save the current configuration to file
*/
private saveConfig(): void {
try {
fs.writeFileSync(this.configPath, JSON.stringify(this.config, null, 2));
} catch (error) {
console.error('Error saving config:', error instanceof Error ? error.message : String(error));
}
}
}