-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonstore.mjs
76 lines (71 loc) · 1.58 KB
/
jsonstore.mjs
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
import * as fs from 'fs'
/**
* A utility class that shows how a File based JSON storage system could work.
* This is not recommended for large databases since every write operation rewrites the entire database.
*/
export class JsonFileStore {
notifyUpdate
dids
keys
privateKeys
credentials
claims
presentations
messages
file
constructor(file) {
this.file = file
this.notifyUpdate = async(oldState, newState) => {
await this.save(newState)
}
this.dids = {}
this.keys = {}
this.privateKeys = {}
this.credentials = {}
this.claims = {}
this.presentations = {}
this.messages = {}
}
static async fromFile(file) {
const store = new JsonFileStore(file)
return await store.load()
}
async load() {
let cache
if (fs.existsSync(this.file)) {
try {
const rawCache = await fs.promises.readFile(this.file, { encoding: 'utf8' })
cache = JSON.parse(rawCache)
} catch (e) {
console.log(e)
cache = {}
}
} else {
cache = {}
}
; ({
dids: this.dids,
keys: this.keys,
credentials: this.credentials,
claims: this.claims,
presentations: this.presentations,
messages: this.messages,
privateKeys: this.privateKeys,
} = {
dids: {},
keys: {},
credentials: {},
claims: {},
presentations: {},
messages: {},
privateKeys: {},
...cache,
})
return this
}
async save(newState) {
await fs.promises.writeFile(this.file, JSON.stringify(newState), {
encoding: 'utf8',
})
}
}