-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
76 lines (69 loc) · 1.83 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
72
73
74
75
76
const level = require('level');
const chainDB = './chaindata';
class Storage {
constructor() {
this.db = level(chainDB);
}
// Add data to levelDB with key/value pair
addLevelDBData(key, value) {
let self = this;
return new Promise(function(resolve, reject) {
self.db.put(key, value, function(err) {
if (err) {
console.log(`BLOCK ${key} FAILED SUBMISSION: ${err}`);
reject(err);
}
resolve(value);
});
});
}
// Get data from levelDB with key
getLevelDBData(key) {
let self = this;
return new Promise((resolve, reject) => {
self.db.get(key, function(err, value) {
if (err) {
console.log(`ERROR: DATA NOT FOUND ${err}`);
reject(err);
}
console.log(value);
resolve(value);
});
});
}
getLevelDBHeight() {
let self = this,
height = 0;
return new Promise((resolve, reject) => {
self.db.createReadStream()
.on('data', function(data) { height++; })
.on('error', function(err) {
return console.log(`ERROR: FAILED TO GET CHAIN HEIGHT ${err}`);
reject(err);
})
.on('close', function() {
height = height - 1;
resolve(height);
});
})
}
// Add data to levelDB with value
addDataToLevelDB(value) {
let self = this;
let dataArray = [];
return new Promise((resolve, reject) => {
self.db.createReadStream()
.on('data', function(data) {
dataArray.push(data);
}).on('error', function(err) {
return console.log(`UNABLE TO READ DATA STREAM: ${err}`)
}).on('close', function() {
resolve(dataArray);
});
});
}
parseBlock(block) {
return (typeof block === 'string') ? JSON.parse(block) : block;
}
}
module.exports = Storage;