fix odl patches
[ccsdk/distribution.git] / dgbuilder / core_nodes / core / 80-template.js
1 /**
2  * Copyright 2013 IBM Corp.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  **/
16
17 module.exports = function(RED) {
18     "use strict";
19     var mustache = require("mustache");
20
21     function TemplateNode(n) {
22         RED.nodes.createNode(this,n);
23         this.name = n.name;
24         this.field = n.field || "payload";
25         this.template = n.template;
26         var node = this;
27
28         var b = node.field.split(".");
29         var i = 0;
30         var m = null;
31         var rec = function(obj) {
32             i += 1;
33             if ((i < b.length) && (typeof obj[b[i-1]] === "object")) {
34                 rec(obj[b[i-1]]); // not there yet - carry on digging
35             }
36             else {
37                  if (i === b.length) { // we've finished so assign the value
38                      obj[b[i-1]] = mustache.render(node.template,m);
39                      node.send(m);
40                  }
41                  else {
42                      obj[b[i-1]] = {}; // needs to be a new object so create it
43                      rec(obj[b[i-1]]); // and carry on digging
44                  }
45             }
46         }
47
48         node.on("input", function(msg) {
49             try {
50                 m = msg;
51                 i = 0;
52                 rec(msg);
53             } catch(err) {
54                 node.error(err.message);
55             }
56         });
57     }
58
59     RED.nodes.registerType("template",TemplateNode);
60     RED.library.register("templates");
61 }