-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.js
71 lines (58 loc) · 1.64 KB
/
Storage.js
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
import { join, dirname } from 'path'
import { Low, JSONFile } from 'lowdb'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url));
export default class Storage {
constructor(filename) {
const path = join(__dirname, 'db.json')
const adapter = new JSONFile(path)
// Set initial state
this.db = new Low(adapter)
}
get initialized() {
return !!this.db.data
}
async initialize() {
await this.db.read()
this.db.data = this.db.data || {
hasRunOnce: false,
nextIssueNo: 1,
}
console.log(`[Storage] Initialized`)
}
async write() {
await this.db.write()
console.log(`[Storage] Written to file`)
}
get nextIssueNo() {
return this.db.data.nextIssueNo
}
async incrementIssueNo() {
this.db.data.nextIssueNo += 1
await this.write()
}
registerPlugin(plugin) {
const name = plugin.constructor.name
// this.db.data[`${name}.seenIds`] ||= []
this.db.data[name] = this.db.data[name] || {
seenIds: []
}
plugin.registerStorage(this)
console.log(`[Storage] Registered plugin ${name}`)
}
unseenIds(provider, ids = []) {
return ids.filter(id => {
console.log(`[Storage.${provider}] Checking if ${id} has been seen`)
return this.db.data[provider].seenIds.includes(id) === false
})
}
addSeenIds(provider, ids = []) {
// Prevent having duplicates saved
const unseen = this.unseenIds(provider, ids)
console.log(`[Storage.${provider}] Marking as seen: ${unseen.join(', ')}`)
this.db.data[provider].seenIds = [
...(this.db.data[provider].seenIds || []),
...unseen
]
}
}