forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceCache.ts
More file actions
65 lines (55 loc) · 2.09 KB
/
Copy pathResourceCache.ts
File metadata and controls
65 lines (55 loc) · 2.09 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import type { ClientJSONSnapshot, EnvironmentJSONSnapshot } from '@clerk/types';
import type { IStorage } from '../provider/singleton/types';
import type { ResourceCache, ResourceCacheInitOptions } from './types';
function createResourceCache<T>(key: string): ResourceCache<T> {
if (!key) {
throw new Error('Clerk: ResourceCache key is required!');
}
let storage: IStorage | null = null;
let itemKey: string | null = null;
const init = (opts: ResourceCacheInitOptions) => {
if (!opts.storage || !opts.publishableKey) {
throw new Error(`Clerk: ResourceCache for ${key} requires storage and publishableKey!`);
}
itemKey = `${key}_${opts.publishableKey.slice(-5)}`;
storage = opts.storage();
};
const checkInit = (): boolean => {
return !!storage && !!itemKey;
};
const assertInitiliazed = () => {
if (!storage || !itemKey) {
throw new Error(`Clerk: ResourceCache for ${key} not initialized!`);
}
};
const load = async (): Promise<T | null> => {
assertInitiliazed();
try {
const value = await storage!.get(itemKey!);
return value ? JSON.parse(value) : null;
} catch (error) {
console.log(`Clerk: Error loading value on ${key} from storage:`, error);
return null;
}
};
const save = async (value: T): Promise<void> => {
assertInitiliazed();
try {
return await storage!.set(itemKey!, JSON.stringify(value));
} catch (error) {
console.log(`Clerk: Error saving value on ${key} in storage:`, error);
}
};
const remove = async (): Promise<void> => {
assertInitiliazed();
try {
return await storage!.set(itemKey!, '');
} catch (error) {
console.log(`Clerk: Error deleting value on ${key} from storage:`, error);
}
};
return { checkInit, init, load, save, remove };
}
export const EnvironmentResourceCache = createResourceCache<EnvironmentJSONSnapshot>('__clerk_cache_environment');
export const ClientResourceCache = createResourceCache<ClientJSONSnapshot>('__clerk_cache_client');
export const SessionJWTCache = createResourceCache<string>('__clerk_cache_session_jwt');