config.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import fs from 'fs-extra';
  2. import path from 'path';
  3. import { fileURLToPath } from 'url';
  4. const __filename = fileURLToPath(import.meta.url);
  5. const __dirname = path.dirname(__filename);
  6. const CONFIG_FILE = path.join(__dirname, 'config.json');
  7. // Default config
  8. const DEFAULT_CONFIG = {
  9. activeTheme: 'default',
  10. postWidth: 'max-w-4xl'
  11. };
  12. // Initialize config file
  13. async function initializeConfig() {
  14. try {
  15. if (!(await fs.pathExists(CONFIG_FILE))) {
  16. await fs.writeJSON(CONFIG_FILE, DEFAULT_CONFIG, { spaces: 2 });
  17. console.log('⚙️ Initialized config system');
  18. }
  19. } catch (error) {
  20. console.error('Error initializing config:', error);
  21. }
  22. }
  23. // Load config data
  24. async function loadConfig() {
  25. try {
  26. if (await fs.pathExists(CONFIG_FILE)) {
  27. return await fs.readJSON(CONFIG_FILE);
  28. }
  29. return DEFAULT_CONFIG;
  30. } catch (error) {
  31. console.error('Error loading config:', error);
  32. return DEFAULT_CONFIG;
  33. }
  34. }
  35. // Save config data
  36. async function saveConfig(configData) {
  37. try {
  38. await fs.writeJSON(CONFIG_FILE, configData, { spaces: 2 });
  39. } catch (error) {
  40. console.error('Error saving config:', error);
  41. throw error;
  42. }
  43. }
  44. // Initialize on load
  45. await initializeConfig();
  46. // Config getters/setters
  47. export async function getConfig() {
  48. return await loadConfig();
  49. }
  50. export async function updateConfig(updates) {
  51. const currentConfig = await loadConfig();
  52. const newConfig = { ...currentConfig, ...updates };
  53. await saveConfig(newConfig);
  54. return newConfig;
  55. }
  56. export async function getActiveThemeId() {
  57. const config = await loadConfig();
  58. return config.activeTheme;
  59. }
  60. export async function setActiveThemeId(themeId) {
  61. return await updateConfig({ activeTheme: themeId });
  62. }
  63. export async function getPostWidth() {
  64. const config = await loadConfig();
  65. return config.postWidth;
  66. }
  67. export async function setPostWidth(width) {
  68. return await updateConfig({ postWidth: width });
  69. }