-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelSandbox.js
80 lines (73 loc) · 2.1 KB
/
LevelSandbox.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
77
78
79
80
/* ===== Persist data with LevelDB ==================
| Learn more: level: https://github.com/Level/level |
/===================================================*/
// Importing the module 'level'
const level = require('level');
// Declaring the folder path that store the data
const chainDB = './chaindata';
// Declaring a class
class LevelSandbox {
// Declaring the class constructor
constructor() {
this.db = level(chainDB);
}
// Get data from levelDB with key (Promise)
getLevelDBData(key){
let self = this;
return new Promise(function(resolve, reject) {
self.db.get(key)
.then( (value) => {
resolve(JSON.parse(value));
},
( err) => {
if(err){
if (err.type == 'NotFoundError') {
reject(err);
}else {
reject(err);
}
}
});
});
}
// Add data to levelDB with key and value (Promise)
addLevelDBData(key, value) {
let self = this;
return new Promise(function(resolve, reject) {
self.db.put(key, JSON.stringify(value), function(err) {
if (err) {
console.log('Block ' + key + ' submission failed', err);
reject(err);
}
console.log(value);
resolve(value);
});
});
}
/**
* Step 2. Implement the getBlocksCount() method
*/
getBlocksCount() {
let self = this;
var block_count = 0;
return new Promise(function(resolve, reject){
self.db.createReadStream()
.on('data', function (data) {
// console.log("DATA HEIGHT ::: !!!!");
// console.log(data);
block_count++;
// console.log("block count : " , block_count);
})
.on('error', function (err) {
reject(err)
})
.on('close', function () {
// console.log("got close event in get Blocks Count");
// console.log(block_count);
resolve(block_count );
});
});
}
}
// Export the class
module.exports.LevelSandbox = LevelSandbox;