File size: 1,573 Bytes
f555806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { apiClient } from '@/utils/api';
import { usingBrowserDb } from '@/utils/env';
import { SettingsData } from '@/types';

const LOCAL_SETTINGS_STORAGE_KEY = 'aitk.browser.settings';

export const DEFAULT_SETTINGS: SettingsData = {
  HF_TOKEN: '',
  TRAINING_FOLDER: '',
  DATASETS_FOLDER: '',
  HF_JOBS_NAMESPACE: '',
  HF_JOBS_DEFAULT_HARDWARE: 'a100-large',
};

const mergeWithDefaults = (data: Partial<SettingsData> | null | undefined): SettingsData => ({
  ...DEFAULT_SETTINGS,
  ...data,
});

export const loadSettings = async (): Promise<SettingsData> => {
  if (usingBrowserDb) {
    if (typeof window === 'undefined') {
      return DEFAULT_SETTINGS;
    }
    try {
      const raw = window.localStorage.getItem(LOCAL_SETTINGS_STORAGE_KEY);
      if (!raw) {
        return DEFAULT_SETTINGS;
      }
      const parsed = JSON.parse(raw);
      return mergeWithDefaults(parsed);
    } catch (error) {
      console.error('Failed to read settings from localStorage:', error);
      return DEFAULT_SETTINGS;
    }
  }

  const response = await apiClient.get('/api/settings');
  return mergeWithDefaults(response.data);
};

export const persistSettings = async (settings: SettingsData): Promise<void> => {
  if (usingBrowserDb) {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      window.localStorage.setItem(LOCAL_SETTINGS_STORAGE_KEY, JSON.stringify(settings));
    } catch (error) {
      console.error('Failed to write settings to localStorage:', error);
    }
    return;
  }

  await apiClient.post('/api/settings', settings);
};