-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.ts
88 lines (72 loc) · 1.88 KB
/
json.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import path from 'path'
import fs from 'fs'
import mkdirp from 'mkdirp'
import { ChunkMeta, DnuStore } from '@/index'
export interface JsonStoreConfig {
[uuid: string]: ChunkMeta
}
export default class JsonStore extends DnuStore {
get store (): Promise<JsonStoreConfig> {
return new Promise((resolve, reject) => {
fs.readFile(this.configPath, (err, data) => {
if (err) return reject(err)
resolve(this.parse(data.toString()))
})
})
}
get configPath (): string {
return path.resolve(this._path, this._name)
}
constructor (
private _path: string,
private _name: string = 'store.json',
private initConfg: JsonStoreConfig = {}
) {
super()
this._path = _path || process.cwd()
this.init()
}
get (uuid: string): ChunkMeta | undefined | Promise<ChunkMeta | undefined> {
return this.store.then(config => {
const meta = config[uuid]
return meta ? meta : undefined
})
}
set (uuid: string, meta: ChunkMeta): PromiseLike<JsonStore> {
return this.store.then(config => {
config[uuid] = meta
this.write(config)
return this
})
}
delete (uuid: string): boolean | Promise<boolean> {
return this.store.then(config => {
delete config[uuid]
try {
this.write(config)
return true
} catch (error) {
return false
}
})
}
exist (uuid: string): boolean | Promise<boolean> {
return this.store.then(config => !!config[uuid])
}
private init () {
mkdirp.sync(this._path)
if (fs.existsSync(this.configPath)) {
fs.unlinkSync(this.configPath)
}
this.write(this.initConfg)
}
private parse (str: any): any {
return JSON.parse(str)
}
private serilize (obj: any): string {
return JSON.stringify(obj)
}
private write (str: object) {
return fs.writeFileSync(this.configPath, this.serilize(str))
}
}