blob: 47b452f7a541ee6a903bf95284caa10d1f2e1d05 (
plain)
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
|
import type { User } from './types';
import { getMe } from './client';
class SessionStore {
me = $state<User | null>(null);
status = $state<'loading' | 'anon' | 'authed'>('loading');
async refresh(): Promise<User | null> {
try {
const { user } = await getMe();
if (!user || typeof user.id !== 'string' || user.id.length === 0) {
this.clear();
return null;
}
this.me = user;
this.status = 'authed';
return user;
} catch (e) {
const status = (e as { status?: number }).status ?? 0;
if (status === 0) {
// network/protocol error: keep previous state so UI can show retry instead
if (this.status === 'loading') this.clear();
return null;
}
this.clear();
return null;
}
}
clear() {
this.me = null;
this.status = 'anon';
}
set(u: User | null) {
if (u && typeof u.id === 'string' && u.id.length > 0) {
this.me = u;
this.status = 'authed';
} else {
this.clear();
}
}
}
export const session: SessionStore = new SessionStore();
|