forked from HySoaKa/node-red-contrib-postgrestor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgrestor.js
91 lines (82 loc) · 2.1 KB
/
postgrestor.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
83
84
85
86
87
88
89
90
91
module.exports = function(RED) {
'use strict';
const mustache = require('mustache');
const PgPool = require('pg').Pool;
const co = require('co');
function PostgresDBNode(n) {
let pgPool = null;
let poolInstance = null;
const node = this;
RED.nodes.createNode(this, n);
node.name = n.name;
node.host = n.host;
node.port = n.port;
node.database = n.database;
node.ssl = n.ssl;
if (node.credentials) {
node.user = node.credentials.user;
node.password = node.credentials.password;
}
class Pool extends PgPool {
constructor() {
if (!poolInstance) {
super({
user: node.user,
password: node.password,
host: node.host,
port: node.port,
database: node.database,
ssl: node.ssl,
max: node.max,
min: node.min,
idleTimeoutMillis: node.idle
});
poolInstance = this;
}
return poolInstance;
}
}
pgPool = new Pool();
this.pgPool = pgPool;
}
RED.nodes.registerType('postgresDB', PostgresDBNode, {
credentials: {
user: {type: 'text'},
password: {type: 'password'}
}
});
function PostgrestorNode(config) {
const node = this;
RED.nodes.createNode(node, config);
node.topic = config.topic;
node.config = RED.nodes.getNode(config.postgresDB);
node.on('input', function(msg) {
const template = {
msg: msg
};
co(
function* () {
let client = yield node.config.pgPool
.connect()
.catch((error) => {
node.error(error);
});
try {
msg.payload = yield client.query(
mustache.render(config.query, template)
);
node.send(msg);
client.release();
} catch (error) {
node.error(error);
client.release();
}
}
);
});
node.on('close', function() {
node.status({});
});
}
RED.nodes.registerType('postgrestor', PostgrestorNode);
};