2 * Copyright 2013 IBM Corp.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 module.exports = function(RED) {
19 var util = require("util");
20 var redis = require("redis");
22 var hashFieldRE = /^([^=]+)=(.*)$/;
24 var redisConnectionPool = function() {
27 get: function(host,port) {
28 var id = host+":"+port;
29 if (!connections[id]) {
30 connections[id] = redis.createClient(port,host);
31 connections[id].on("error",function(err) {
32 util.log("[redis] "+err);
34 connections[id].on("connect",function() {
35 util.log("[redis] connected to "+host+":"+port);
37 connections[id]._id = id;
38 connections[id]._nodeCount = 0;
40 connections[id]._nodeCount += 1;
41 return connections[id];
43 close: function(connection) {
44 connection._nodeCount -= 1;
45 if (connection._nodeCount === 0) {
47 clearTimeout(connection.retry_timer);
50 delete connections[connection._id];
58 function RedisOutNode(n) {
59 RED.nodes.createNode(this,n);
60 this.port = n.port||"6379";
61 this.hostname = n.hostname||"127.0.0.1";
63 this.structtype = n.structtype;
65 this.client = redisConnectionPool.get(this.hostname,this.port);
67 if (this.client.connected) {
68 this.status({fill:"green",shape:"dot",text:"connected"});
70 this.status({fill:"red",shape:"ring",text:"disconnected"},true);
74 this.client.on("end", function() {
75 node.status({fill:"red",shape:"ring",text:"disconnected"});
77 this.client.on("connect", function() {
78 node.status({fill:"green",shape:"dot",text:"connected"});
81 this.on("input", function(msg) {
82 var k = this.key || msg.topic;
84 if (this.structtype == "string") {
85 this.client.set(k,RED.util.ensureString(msg.payload));
86 } else if (this.structtype == "hash") {
87 var r = hashFieldRE.exec(msg.payload);
89 this.client.hset(k,r[1],r[2]);
91 this.warn("Invalid payload for redis hash");
93 } else if (this.structtype == "set") {
94 this.client.sadd(k,msg.payload);
95 } else if (this.structtype == "list") {
96 this.client.rpush(k,msg.payload);
99 this.warn("No key or topic set");
102 this.on("close", function() {
103 redisConnectionPool.close(node.client);
106 RED.nodes.registerType("redis out",RedisOutNode);