59 lines
1.2 KiB
TypeScript
59 lines
1.2 KiB
TypeScript
import { browser } from '$app/environment';
|
|||
|
|
import { writable } from 'svelte/store';
|
||
|
|
|
||
|
|
export type OperatorSession = {
|
||
|
|
name: string;
|
||
|
|
email: string;
|
||
|
|
role: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
const STORAGE_KEY = 'data-entry-app-operator-session';
|
||
|
|
|
||
|
|
function readSession(): OperatorSession | null {
|
||
|
|
if (!browser) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
const value = localStorage.getItem(STORAGE_KEY);
|
||
|
|
if (!value) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
return JSON.parse(value) as OperatorSession;
|
||
|
|
} catch {
|
||
|
|
localStorage.removeItem(STORAGE_KEY);
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function createOperatorSessionStore() {
|
||
|
|
const store = writable<OperatorSession | null>(readSession());
|
||
|
|
|
||
|
|
if (browser) {
|
||
|
|
window.addEventListener('storage', (event) => {
|
||
|
|
if (event.key === STORAGE_KEY) {
|
||
|
|
store.set(readSession());
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
subscribe: store.subscribe,
|
||
|
|
set(session: OperatorSession) {
|
||
|
|
if (browser) {
|
||
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(session));
|
||
|
|
}
|
||
|
|
store.set(session);
|
||
|
|
},
|
||
|
|
clear() {
|
||
|
|
if (browser) {
|
||
|
|
localStorage.removeItem(STORAGE_KEY);
|
||
|
|
}
|
||
|
|
store.set(null);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export const operatorSession = createOperatorSessionStore();
|