nxtgauge-admin-solid/src/lib/runtime/storage.ts

80 lines
2.2 KiB
TypeScript
Raw Normal View History

export type RuntimeRecordType = 'role' | 'dashboard' | 'onboarding';
export type RuntimeRecordStatus = 'draft' | 'published';
const KEY = 'nxtgauge_admin_runtime_builder_v1';
type RuntimeStore = {
role: Record<string, RuntimeStoredRecord<unknown>>;
dashboard: Record<string, RuntimeStoredRecord<unknown>>;
onboarding: Record<string, RuntimeStoredRecord<unknown>>;
};
export type RuntimeStoredRecord<T> = {
status: RuntimeRecordStatus;
updatedAt: string;
payload: T;
};
export type RuntimeListItem<T> = RuntimeStoredRecord<T> & {
key: string;
};
function emptyStore(): RuntimeStore {
return { role: {}, dashboard: {}, onboarding: {} };
}
function readStore(): RuntimeStore {
if (typeof window === 'undefined') return emptyStore();
const raw = window.localStorage.getItem(KEY);
if (!raw) return emptyStore();
try {
const parsed = JSON.parse(raw) as Partial<RuntimeStore>;
return {
role: parsed.role || {},
dashboard: parsed.dashboard || {},
onboarding: parsed.onboarding || {},
};
} catch {
return emptyStore();
}
}
function writeStore(store: RuntimeStore) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(KEY, JSON.stringify(store));
}
export function saveRuntimeConfig(type: RuntimeRecordType, key: string, payload: unknown, status: RuntimeRecordStatus) {
const normalizedKey = key.trim();
if (!normalizedKey) return;
const store = readStore();
store[type][normalizedKey] = {
status,
updatedAt: new Date().toISOString(),
payload,
};
writeStore(store);
}
export function listRuntimeConfigs<T>(type: RuntimeRecordType): Array<RuntimeListItem<T>> {
const store = readStore();
return Object.entries(store[type])
.map(([key, value]) => ({ key, ...(value as RuntimeStoredRecord<T>) }))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
}
export function getRuntimeConfig<T>(type: RuntimeRecordType, key: string): RuntimeStoredRecord<T> | null {
const record = readStore()[type][key];
return (record as RuntimeStoredRecord<T>) || null;
}
export function deleteRuntimeConfig(type: RuntimeRecordType, key: string): boolean {
const store = readStore();
if (!store[type][key]) return false;
delete store[type][key];
writeStore(store);
return true;
}