forked from ethereum/mist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
74 lines (61 loc) · 1.77 KB
/
db.js
File metadata and controls
74 lines (61 loc) · 1.77 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
65
66
67
68
69
70
71
72
73
74
const fs = require('fs');
const Q = require('bluebird');
const Loki = require('lokijs');
const Settings = require('./settings');
const log = require('./utils/logger').create('Db');
let db;
exports.init = () => {
const filePath = Settings.dbFilePath;
return Q.try(() => {
// if db file doesn't exist then create it
try {
log.debug(`Check that db exists and it's writeable: ${filePath}`);
fs.accessSync(filePath, fs.R_OK | fs.W_OK);
return Q.resolve();
} catch (err) {
log.info(`Creating db: ${filePath}`);
const tempdb = new Loki(filePath, {
env: 'NODEJS',
autoload: false,
});
return new Q.promisify(tempdb.saveDatabase, { context: tempdb })();
}
})
.then(() => {
log.info(`Loading db: ${filePath}`);
return new Q((resolve, reject) => {
db = new Loki(filePath, {
env: 'NODEJS',
autosave: true,
autosaveInterval: 5000,
autoload: true,
autoloadCallback(err) {
if (err) {
log.error(err);
reject(new Error('Error instantiating db'));
}
resolve();
},
});
});
});
};
exports.getCollection = (name) => {
if (!db.getCollection(name)) {
db.addCollection(name, {
unique: ['_id']
});
}
return db.getCollection(name);
};
exports.close = () => {
return new Q((resolve, reject) => {
db.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};