Javascript: Data source function

Date: 2017-01-09
define([], function () {
    var exports = {};

    exports.jsonToJS = function (str) {
        return JSON.parse(str);
    };

    var xmlNodeToJS = function (xml) {
        try {
            // Create the return object
            var obj = {};
            if (xml.nodeType === 1) { // element
                // do attributes
                if (xml.attributes.length > 0) {
                    for (var j = 0; j < xml.attributes.length; j++) {
                        var attribute = xml.attributes.item(j);
                        obj['@' + attribute.nodeName] = attribute.nodeValue;
                    }
                }
            } else if (xml.nodeType === 3 || xml.nodeType === 4) { // text
                obj = xml.nodeValue;
            }

            // do children
            if (xml.hasChildNodes()) {
                for (var i = 0; i < xml.childNodes.length; i++) {
                    var item = xml.childNodes.item(i);
                    var nodeName = item.nodeName;
                    if (typeof (obj[nodeName]) === 'undefined') {
                        obj[nodeName] = xmlNodeToJS(item);
                    } else {
                        if (typeof (obj[nodeName].push) === 'undefined') {
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        obj[nodeName].push(xmlNodeToJS(item));
                    }
                }
            }
            return obj;
        } catch (e) {
            return {};
        }
    };
    
    exports.replaceTextAndCData = function(obj) {
        if (typeof(obj) === "object") {                  
          if ('#text' in obj) {
            return obj['#text'];
          }          
          if ('#cdata-section' in obj) {
            return obj['#cdata-section'];
          }          
                 
          for(var key in obj) {
            if (obj.hasOwnProperty(key)) {
                obj[key] = exports.replaceTextAndCData(obj[key]);          
              
            }            
          }                
        }
        return obj;
    };

    exports.xmlToJS = function (str, replaceTextAndCData) {
        try {
            if ('DOMParser' in window) {
                var parser = new window.DOMParser();
                var xmlDoc = parser.parseFromString(str.trim(), 'text/xml');
                var obj = xmlNodeToJS(xmlDoc);               
                if (replaceTextAndCData) {
                  return exports.replaceTextAndCData(obj);
                }
                return obj;
            }
        } catch (ex) {
            return {};
        }
    };

    exports.queryObject = function (obj, path) {
        if (typeof path == 'undefined' || path.trim() == "") throw "Het ingestelde querypad bestaat niet";
        var curObj = obj;
        var result = [];
        var parts = path.split('.');
        parts.forEach(function (part, i) {
            if (part in curObj) {
                if (i === parts.length - 1) {
                    var resultObj = curObj[part];
                    var type = resultObj.constructor.name;
                    if (type == 'Array') {
                        result = [];
                    } else if (type == "Object") {
                        result = {};
                    }
                    var keys = Object.keys(resultObj);
                    for (var prop in keys) {
                        if (type == 'Array') {
                            result[prop] = resultObj[prop];
                        } else if (type == "Object") {
                            var propName = keys[prop];
                            result[propName] = resultObj[propName];
                        }
                    }
                } else {
                    curObj = curObj[part];
                }
            } else {
                return false;
            }
        });
        return result;
    };

    exports.compare = function (a, b, dir) {
        if (!dir) dir = 1;
        var cmp = 0;
        if (a > b) cmp = 1;
        else if (a < b) cmp = -1;
        return dir * cmp;
    };

    exports.compareString = function (a, b, dir) {
        if (!dir) dir = 1;
        return dir * ('' + a).localeCompare('' + b);
    };

    exports.format = function (str) {
        var i;
        for (i = 1; i < arguments.length; i++) {
            str = str.replace('{' + (i - 1) + '}', arguments[i]);
        }
        return str;
    };

    exports.array = function (obj) {
        if (obj !== null && obj !== undefined) {
            if (Array.isArray(obj)) {
                return obj;
            } else {
                return [obj];
            }
        }
        return [];
    };

    exports.truncateSmart = function (str, limit) {
        var bits, i;
        bits = ('' + str).split('');
        if (bits.length > limit) {
            for (i = bits.length - 1; i > -1; --i) {
                if (i > limit) {
                    bits.length = i;
                } else if (' ' === bits[i]) {
                    bits.length = i;
                    break;
                }
            }
            bits.push('...');
        }
        return bits.join('');
    };

    return exports;
});

define(['bluebird.min', 'jquery', 'lib/moment-with-locales'], function () {
    var Promise = require('bluebird.min');
    var $ = require('jquery');
    var moment = require('lib/moment-with-locales');    

    var compare = function(a, b) {
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };
    
    var getQueryDataFromFunction = function(fnText) {
        return new Promise(function (resolve, reject) {
          try {
              var fullFnText = "return function($, Promise, moment, tools) { var window, document, alert, confirm, self, parent, global; return new Promise(function(resolve, reject) { try { " + fnText + " } catch(e) { reject(e); } })};";
              var fn = new Function(fullFnText)();

              fn($, Promise, moment, dataTools)
              .timeout(10000)
              .then(function(data) {
                  resolve(data);
              })
              .catch(function(err) {
                  var error = err.toString();
                  if (err.stack) {
                      error = err.stack;
                  }
                  console.warn('getQueryDataFromFunction', error);
                  reject(error);
              });
            } catch(err) {
               var error = err.toString();
                  if (err.stack) {
                      error = err.stack;
                  }
                  console.warn('getQueryDataFromFunction', error);
                  reject(error);
            }
        });
    };
    
    return exports;
});

var url = 'http://ac.weatheronyoursite.com/narrowcast_travelweather_daypart.xml';
$.ajax({
        url: url,
        cache: false
    })
    .done(function(resultData, result, xhr) {
        try {
            var data = tools.xmlToJS(xhr.responseText, true);
            var landen = tools.queryObject(data, 'WEERONLINE.continent.land');
            moment.locale('nl') 
            // land filteren
            var land = landen.filter(land => land.landnaam === 'Nederland')[0];
            var plaats = land.plaats.filter(plaats => plaats.plaatsnaam === 'Rotterdam')[0];
            var weerinfo = plaats.weerinfo[0];
            var details = {
                naam: plaats.plaatsnaam,
                dag : moment(weerinfo.datum).format('dddd')
            };

            details.ochtend = weerinfo.weerdata.filter(weerdata => weerdata.dagdeel === 'ochtend')[0];
            details.middag = weerinfo.weerdata.filter(weerdata => weerdata.dagdeel === 'middag')[0];
            details.avond = weerinfo.weerdata.filter(weerdata => weerdata.dagdeel === 'avond')[0];
        
            resolve(details);
        } catch (err) {
            reject(err);
        }
    })
    .fail(reject);
5820cookie-checkJavascript: Data source function