-
Notifications
You must be signed in to change notification settings - Fork 2
/
storage.js
59 lines (55 loc) · 1.46 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
var dirty = require('dirty');
var db = dirty('user.db');
const async = require('async')
const Promise = require('bluebird')
let initialized
const storage = async () => {
const result = await new Promise((resolve, reject) => {
if (initialized) {
resolve(initialized)
}
db.on('load', function () {
const storage = {
get: (key) => {
return new Promise.resolve(db.get(key))
},
set: (key, value) => {
return new Promise((resolve, reject) => {
db.set(key, value, (err, res) => {
if (err) return reject(err)
return resolve(res)
})
})
},
remove: (...keys) => {
return Promise.all(keys.map((k) => {
return new Promise((resolve, reject) => {
db.rm(k, (err, res) => {
if (err) return reject(err)
return resolve(res)
})
})
}))
},
clear: () => {
return new Promise((resolve, reject) => {
let keys = []
db.forEach((key, val) => {
keys.push(key)
})
async.forEach(keys, (key, next) => {
db.rm(key, next)
}, (err, res) => {
if (err) return reject(err)
resolve(res)
})
})
}
}
initialized = storage
resolve(storage)
});
})
return result
}
module.exports = storage