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 function ChangeNode(n) {
20 RED.nodes.createNode(this, n);
21 this.action = n.action;
22 this.property = n.property || "";
23 this.from = n.from || " ";
24 this.to = n.to || " ";
25 this.reg = (n.reg === null || n.reg);
27 if (node.reg === false) {
28 this.from = this.from.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
30 var makeNew = function( stem, path, value ) {
31 var lastPart = (arguments.length === 3) ? path.pop() : false;
32 for (var i = 0; i < path.length; i++) {
33 stem = stem[path[i]] = stem[path[i]] || {};
35 if (lastPart) { stem = stem[lastPart] = value; }
39 this.on('input', function (msg) {
40 if (node.action == "change") {
42 node.re = new RegExp(this.from, "g");
44 node.error(e.message);
46 if (typeof msg[node.property] === "string") {
47 msg[node.property] = (msg[node.property]).replace(node.re, node.to);
50 //else if (node.action == "replace") {
51 //if (node.to.indexOf("msg.") == 0) {
52 //msg[node.property] = eval(node.to);
55 //msg[node.property] = node.to;
58 else if (node.action == "replace") {
59 if (node.to.indexOf("msg.") === 0) {
60 makeNew( msg, node.property.split("."), eval(node.to) );
63 makeNew( msg, node.property.split("."), node.to );
65 //makeNew( msg, node.property.split("."), node.to );
67 else if (node.action == "delete") {
68 delete(msg[node.property]);
73 RED.nodes.registerType("change", ChangeNode);