forked from node-red/node-red-nodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
67-leveldb.js
82 lines (74 loc) · 2.86 KB
/
67-leveldb.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
81
82
module.exports = function(RED) {
"use strict";
var lvldb = require('level');
function LevelNode(n) {
RED.nodes.createNode(this,n);
this.dbname = n.db;
this.encoding = n.encoding || "utf8";
this.ready = false;
var node = this;
lvldb(this.dbname, {valueEncoding:this.encoding}, function(err, db) {
if (err) { node.error(err); }
node.db = db;
node.db.on('ready', function() { node.ready = true; });
node.db.on('closing', function() { node.ready = false; });
});
node.on('close', function() {
if (node.db) {
node.ready = false;
node.db.close();
}
});
}
RED.nodes.registerType("leveldbase",LevelNode);
function LevelDBNodeIn(n) {
RED.nodes.createNode(this,n);
this.level = n.level;
this.levelConfig = RED.nodes.getNode(this.level);
var node = this;
node.on("input", function(msg) {
if (node.levelConfig && node.levelConfig.ready) {
var key = msg.topic.toString();
if (key && (key.length > 0)) {
node.levelConfig.db.get(msg.topic, function(err, value) {
if (err) {
//node.warn(err);
// for some reason they treat nothing found as an error...
msg.payload = null; // so we should return null
}
else { msg.payload = value; }
node.send(msg);
});
}
else { node.error("Cannot make key string from msg.topic"); }
}
else { node.error("Database not ready",msg); }
});
}
RED.nodes.registerType("leveldb in",LevelDBNodeIn);
function LevelDBNodeOut(n) {
RED.nodes.createNode(this,n);
this.level = n.level;
this.operation = n.operation;
this.levelConfig = RED.nodes.getNode(this.level);
var node = this;
node.on("input", function(msg) {
if (node.levelConfig && node.levelConfig.ready) {
var key = msg.topic.toString();
if (key && (key.length > 0)) {
if (node.operation === "delete") {
node.levelConfig.db.del(msg.topic);
}
else {
node.levelConfig.db.put(msg.topic, msg.payload, function(err) {
if (err) { node.error(err,msg); }
});
}
}
else { node.error("Cannot make key string from msg.topic",msg); }
}
else { node.error("Database not ready",msg); }
});
}
RED.nodes.registerType("leveldb out",LevelDBNodeOut);
}