forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhitelist-database.ts
More file actions
70 lines (56 loc) · 2.19 KB
/
Copy pathwhitelist-database.ts
File metadata and controls
70 lines (56 loc) · 2.19 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
66
67
68
69
70
/**
* Copyright (c) 2021 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { isStringArray } from 'typescript-guard'
import BaseDatabase from "./common/base-database"
import { WHITELIST_KEY } from "./common/constant"
import { extractNamespace, isExportData, isLegacyVersion } from './common/migratable'
import type { BrowserMigratable } from './types'
class WhitelistDatabase extends BaseDatabase implements BrowserMigratable<'__whitelist__'> {
namespace: '__whitelist__' = '__whitelist__'
private async update(toUpdate: string[]): Promise<void> {
await this.setByKey(WHITELIST_KEY, toUpdate || [])
}
async selectAll(): Promise<string[]> {
const exist = await this.storage.getOne<string[]>(WHITELIST_KEY)
return exist || []
}
async add(white: string): Promise<void> {
const exist = await this.selectAll()
if (exist.includes(white)) return
await this.update([...exist, white])
}
async remove(white: string): Promise<void> {
const exist = await this.selectAll()
const toUpdate = exist?.filter?.(w => w !== white) || []
return await this.update(toUpdate)
}
async exist(white: string): Promise<boolean> {
const exist = await this.selectAll()
return exist?.includes(white)
}
async importData(data: unknown): Promise<void> {
if (!isExportData(data)) return
const toImport = isLegacyVersion(data)
? this.parseLegacyData(data)
: extractNamespace(data, this.namespace, isStringArray)
const exist = await this.selectAll()
toImport?.forEach(white => !exist.includes(white) && exist.push(white))
await this.update(exist)
}
/**
* @deprecated Only for legacy data, will be removed in future version
*/
private parseLegacyData(data: tt4b.backup.ExportData): string[] {
const toMigrate = (data as any)[WHITELIST_KEY]
return isStringArray(toMigrate) ? toMigrate : []
}
exportData(): Promise<string[]> {
return this.selectAll()
}
}
const whitelistDatabase = new WhitelistDatabase()
export default whitelistDatabase