-
Notifications
You must be signed in to change notification settings - Fork 34
/
session.ts
51 lines (45 loc) · 1.22 KB
/
session.ts
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
import * as SecureStore from 'expo-secure-store';
import InvariantViolated from '@/errors/InvariantViolated';
const SESSION_KEY = 'kitsu-session';
export type LoggedInSession = {
loggedIn: true;
accessToken: string;
refreshToken: string;
expiresAt: Date;
};
export type LoggedOutSession = {
loggedIn: false;
};
export type Session = LoggedInSession | LoggedOutSession;
/**
* Load the session from storage
* @returns The session object
*/
export function load(): Session {
try {
const serialized = SecureStore.getItem(SESSION_KEY);
return serialized ? JSON.parse(serialized) : { loggedIn: false };
} catch (cause) {
console.error(
new InvariantViolated('Error while parsing session', { cause })
);
return { loggedIn: false };
}
}
/**
* Save the session to storage
* @param session The session object
*/
export function save(session: Session) {
const serialized = JSON.stringify(session);
SecureStore.setItem(SESSION_KEY, serialized);
}
/**
* Clear the session from storage
*/
export function clear() {
SecureStore.deleteItemAsync(SESSION_KEY).catch((cause) => {
// @TODO: Replace this with Sentry
console.error(new InvariantViolated('Failed to clear session'), { cause });
});
}