-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathwhitelist-database.ts
More file actions
64 lines (54 loc) · 1.9 KB
/
whitelist-database.ts
File metadata and controls
64 lines (54 loc) · 1.9 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
/**
* Copyright (c) 2021 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import BaseDatabase from "./common/base-database"
import { WHITELIST_KEY } from "./common/constant"
class WhitelistDatabase extends BaseDatabase {
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)
}
/**
* Add listener to listen changes
*
* @since 0.1.9
*/
addChangeListener(listener: (whitelist: string[]) => void) {
const storageListener = (
changes: { [key: string]: chrome.storage.StorageChange },
_areaName: chrome.storage.AreaName,
) => {
const changeInfo = changes[WHITELIST_KEY]
changeInfo && listener(changeInfo.newValue || [])
}
chrome.storage.onChanged.addListener(storageListener)
}
async importData(data: any): Promise<void> {
const toMigrate = data[WHITELIST_KEY]
if (!Array.isArray(toMigrate)) return
const exist = await this.selectAll()
toMigrate.forEach(white => !exist.includes(white) && exist.push(white))
await this.update(exist)
}
}
export default WhitelistDatabase