-
Notifications
You must be signed in to change notification settings - Fork 1
/
data-storage.service.ts
63 lines (56 loc) · 1.89 KB
/
data-storage.service.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
import { CacheStorageProvider, CacheValue } from './cache.service';
import { KeyValueStorage } from '@ionic-enterprise/secure-storage/ngx';
import { Injectable, OnInit } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataStorageService implements CacheStorageProvider {
private ready: Promise<void>;
constructor(private storage: KeyValueStorage) {
this.createStorage();
}
public async readValue(key: string): Promise<CacheValue> {
try {
await this.ready;
return JSON.parse(await this.storage.get(key));
} catch (error) {
console.error('readValue', error);
return undefined;
}
}
public async writeValue(key: string, value: CacheValue): Promise<void> {
await this.ready;
await this.storage.set(key, JSON.stringify(value));
}
public async clear(): Promise<void> {
await this.ready;
await this.storage.clear();
}
/**
* Create the storage specifying the encryption key to be used
*
* @returns Promise
*/
private async createStorage() {
this.ready = this.storage.create('super-secret-key');
this.ready.catch((error) => this.handleCreateError(error));
}
/**
* If the encryption key is invalid we want to clear our storage
*
* @param error
*/
private async handleCreateError(error: Error): Promise<void> {
if (error?.message?.includes('may be invalid')) {
try {
await this.storage.destroyStorage();
await this.createStorage();
console.log('Recreated storage as encryption key was invalid');
} catch (clearError) {
console.error('handleCreateError.destroyStorage Failure', clearError);
}
} else {
console.error('handleCreateError', error);
}
}
}