-
Notifications
You must be signed in to change notification settings - Fork 86
/
storage.ts
98 lines (81 loc) · 2.63 KB
/
storage.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { IdbKeyVal } from './db';
export const KEY_STORAGE_KEY = 'identity';
export const KEY_STORAGE_DELEGATION = 'delegation';
export const KEY_VECTOR = 'iv';
// Increment if any fields are modified
export const DB_VERSION = 1;
export const isBrowser = typeof window !== 'undefined';
/**
* Interface for persisting user authentication data
*/
export interface AuthClientStorage {
get(key: string): Promise<string | null>;
set(key: string, value: string): Promise<void>;
remove(key: string): Promise<void>;
}
/**
* Legacy implementation of AuthClientStorage, for use where IndexedDb is not available
*/
export class LocalStorage implements AuthClientStorage {
constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {}
public get(key: string): Promise<string | null> {
return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));
}
public set(key: string, value: string): Promise<void> {
this._getLocalStorage().setItem(this.prefix + key, value);
return Promise.resolve();
}
public remove(key: string): Promise<void> {
this._getLocalStorage().removeItem(this.prefix + key);
return Promise.resolve();
}
private _getLocalStorage() {
if (this._localStorage) {
return this._localStorage;
}
const ls =
typeof window === 'undefined'
? typeof global === 'undefined'
? typeof self === 'undefined'
? undefined
: self.localStorage
: global.localStorage
: window.localStorage;
if (!ls) {
throw new Error('Could not find local storage.');
}
return ls;
}
}
/**
* IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}
*
* It replaces {@link LocalStorage}
* @see implements {@link AuthClientStorage}
*/
export class IdbStorage implements AuthClientStorage {
// Intializes a KeyVal on first request
private initializedDb: IdbKeyVal | undefined;
get _db(): Promise<IdbKeyVal> {
return new Promise(resolve => {
if (this.initializedDb) resolve(this.initializedDb);
IdbKeyVal.create({ version: DB_VERSION }).then(db => {
this.initializedDb = db;
resolve(db);
});
});
}
public async get(key: string): Promise<string | null> {
const db = await this._db;
return await db.get<string>(key);
// return (await db.get<string>(key)) ?? null;
}
public async set(key: string, value: string): Promise<void> {
const db = await this._db;
await db.set(key, value);
}
public async remove(key: string): Promise<void> {
const db = await this._db;
await db.remove(key);
}
}