109 lines
2.8 KiB
JavaScript
109 lines
2.8 KiB
JavaScript
/**
|
|
* Chat Switchboard - Storage Module
|
|
* Abstraction layer for storage (localStorage now, API later)
|
|
*/
|
|
|
|
const Storage = {
|
|
// Backend mode: 'local' or 'api'
|
|
mode: 'local',
|
|
apiBase: '/api',
|
|
|
|
async get(key, defaultValue = null) {
|
|
if (this.mode === 'api') {
|
|
try {
|
|
const response = await fetch(`${this.apiBase}/storage/${key}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
return defaultValue;
|
|
} catch (e) {
|
|
console.error('Storage API get error:', e);
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
// Local storage
|
|
try {
|
|
const item = localStorage.getItem(key);
|
|
return item ? JSON.parse(item) : defaultValue;
|
|
} catch (e) {
|
|
console.error('Storage get error:', e);
|
|
return defaultValue;
|
|
}
|
|
},
|
|
|
|
async set(key, value) {
|
|
if (this.mode === 'api') {
|
|
try {
|
|
await fetch(`${this.apiBase}/storage/${key}`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(value)
|
|
});
|
|
} catch (e) {
|
|
console.error('Storage API set error:', e);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Local storage
|
|
try {
|
|
localStorage.setItem(key, JSON.stringify(value));
|
|
} catch (e) {
|
|
console.error('Storage set error:', e);
|
|
}
|
|
},
|
|
|
|
async remove(key) {
|
|
if (this.mode === 'api') {
|
|
try {
|
|
await fetch(`${this.apiBase}/storage/${key}`, { method: 'DELETE' });
|
|
} catch (e) {
|
|
console.error('Storage API remove error:', e);
|
|
}
|
|
return;
|
|
}
|
|
|
|
try {
|
|
localStorage.removeItem(key);
|
|
} catch (e) {
|
|
console.error('Storage remove error:', e);
|
|
}
|
|
},
|
|
|
|
// Switch to API mode
|
|
useApi(baseUrl = '/api') {
|
|
this.mode = 'api';
|
|
this.apiBase = baseUrl;
|
|
},
|
|
|
|
// Switch to local mode
|
|
useLocal() {
|
|
this.mode = 'local';
|
|
}
|
|
};
|
|
|
|
// For standalone HTML, use sync versions
|
|
const StorageSync = {
|
|
get(key, defaultValue = null) {
|
|
try {
|
|
const item = localStorage.getItem(key);
|
|
return item ? JSON.parse(item) : defaultValue;
|
|
} catch (e) {
|
|
return defaultValue;
|
|
}
|
|
},
|
|
set(key, value) {
|
|
try {
|
|
localStorage.setItem(key, JSON.stringify(value));
|
|
} catch (e) {
|
|
console.error('Storage set error:', e);
|
|
}
|
|
},
|
|
remove(key) {
|
|
try {
|
|
localStorage.removeItem(key);
|
|
} catch (e) {}
|
|
}
|
|
};
|