Example #1
0
 self.assemble = function assemble() {
   if (arguments.length === 1 && _.isFunction(arguments[0])) {
     assembleCallback(arguments[0]);
   }
   return assemblePromise();
 };
Example #2
0
 $scope.canMoveColumnRight = function canMoveColumn(columnName) {
   return (
     _.isFunction($scope.onMoveColumn)
     && $scope.columns.indexOf(columnName) < $scope.columns.length - 1
   );
 };
Example #3
0
 function onComplete(error) {
   done = true;
   if (_.isFunction(opts.done)) {
     opts.done(error);
   }
 }
Example #4
0
 proxyActive (sessionId) {
   const dstSession = this.sessions[sessionId];
   return dstSession && _.isFunction(dstSession.proxyActive) && dstSession.proxyActive(sessionId);
 }
Example #5
0
		    let byes = _.filter(extensions.map((what) => spawn(what)),x => _.isFunction(x))
Example #6
0
 vis.handler.charts.forEach(function (chart) {
   expect(_.isFunction(chart.draw())).to.be(true);
 });
Example #7
0
 return _.reject(types, function (t) {
     return _.isFunction(t) || _.isObject(t) || _.isArray(t);
 });
Example #8
0
 }, function (err, scrobbles) {
     /* istanbul ignore else */
     if (_.isFunction(cb)) { cb(err); }
 });
 return run(dispatch).catch(function(error) {
   //console.log('dispatch error:', error);
   assert(_.isFunction(error.actionAsync), "error.actionAsync should be a function");
   expect(error.request[0]).to.be.equal(param);
   expect(error.error.name).to.be.equal('myError');
 });
Example #10
0
Interceptor.prototype.filteringPath = function filteringPath() {
    if (_.isFunction(arguments[0])) {
        this.scope.transformFunction = arguments[0];
    }
    return this;
};
Example #11
0
Interceptor.prototype.reply = function reply(statusCode, body, rawHeaders) {
    if (arguments.length <= 2 && _.isFunction(statusCode)) {
        body = statusCode;
        statusCode = 200;
    }

    this.statusCode = statusCode;

    _.defaults(this.options, this.scope.scopeOptions);

    // convert rawHeaders from Array to Object
    var headers = common.headersArrayToObject(rawHeaders);

    if (this.scope._defaultReplyHeaders) {
        headers = headers || {};
        headers = mixin(this.scope._defaultReplyHeaders, headers);
    }

    if (this.scope.date) {
        headers = headers || {};
        headers['date'] = this.scope.date.toUTCString();
    }

    if (headers !== undefined) {
        this.rawHeaders = [];

        // makes sure all keys in headers are in lower case
        for (var key in headers) {
            if (headers.hasOwnProperty(key)) {
                this.rawHeaders.push(key);
                this.rawHeaders.push(headers[key]);
            }
        }

        //  We use lower-case headers throughout Nock.
        this.headers = common.headersFieldNamesToLowerCase(headers);

        debug('reply.headers:', this.headers);
        debug('reply.rawHeaders:', this.rawHeaders);
    }

    //  If the content is not encoded we may need to transform the response body.
    //  Otherwise we leave it as it is.
    if (!common.isContentEncoded(this.headers)) {
        if (body && typeof(body) !== 'string' &&
            typeof(body) !== 'function' &&
            !Buffer.isBuffer(body) &&
            !common.isStream(body)) {
            try {
                body = stringify(body);
                if (!this.headers) {
                    this.headers = {};
                }
                if (!this.headers['content-type']) {
                    this.headers['content-type'] = 'application/json';
                }
                if (this.scope.contentLen) {
                    this.headers['content-length'] = body.length;
                }
            } catch(err) {
                throw new Error('Error encoding response body into JSON');
            }
        }
    }

    this.body = body;

    this.scope.add(this._key, this, this.scope, this.scopeOptions);
    return this.scope;
};
Example #12
0
 var checkHeaders = function(header) {
     if (_.isFunction(header.value)) {
         return header.value(options.getHeader(header.name));
     }
     return common.matchStringOrRegexp(options.getHeader(header.name), header.value);
 };
Example #13
0
Interceptor.prototype.match = function match(options, body, hostNameOnly) {
    if (debug.enabled) {
        debug('match %s, body = %s', stringify(options), stringify(body));
    }

    if (hostNameOnly) {
        return options.hostname === this.scope.urlParts.hostname;
    }

    var method = (options.method || 'GET').toUpperCase()
        , path = options.path
        , matches
        , matchKey
        , proto = options.proto;

    if (this.scope.transformPathFunction) {
        path = this.scope.transformPathFunction(path);
    }
    if (typeof(body) !== 'string') {
        body = body.toString();
    }
    if (this.scope.transformRequestBodyFunction) {
        body = this.scope.transformRequestBodyFunction(body, this._requestBody);
    }

    var checkHeaders = function(header) {
        if (_.isFunction(header.value)) {
            return header.value(options.getHeader(header.name));
        }
        return common.matchStringOrRegexp(options.getHeader(header.name), header.value);
    };

    if (!this.scope.matchHeaders.every(checkHeaders) ||
        !this.interceptorMatchHeaders.every(checkHeaders)) {
        this.scope.logger('headers don\'t match');
        return false;
    }

    var reqHeadersMatch =
        ! this.reqheaders ||
        Object.keys(this.reqheaders).every(this.reqheaderMatches.bind(this, options));

    if (!reqHeadersMatch) {
        return false;
    }

    function reqheaderContains(header) {
        return _.has(options.headers, header);
    }

    var reqContainsBadHeaders =
        this.badheaders &&
        _.some(this.badheaders, reqheaderContains);

    if (reqContainsBadHeaders) {
        return false;
    }

    //  If we have a filtered scope then we use it instead reconstructing
    //  the scope from the request options (proto, host and port) as these
    //  two won't necessarily match and we have to remove the scope that was
    //  matched (vs. that was defined).
    if (this.__nock_filteredScope) {
        matchKey = this.__nock_filteredScope;
    } else {
        matchKey = proto + '://' + options.host;
        if (
            options.port && options.host.indexOf(':') < 0 &&
            (options.port !== 80 || options.proto !== 'http') &&
            (options.port !== 443 || options.proto !== 'https')
        ) {
            matchKey += ":" + options.port;
        }
    }

    // Match query strings when using query()
    var matchQueries = true;
    var queryIndex = -1;
    var queryString;
    var queries;

    if (this.queries && (queryIndex = path.indexOf('?')) !== -1) {
        queryString = path.slice(queryIndex + 1);
        queries = qs.parse(queryString);

        // Only check for query string matches if this.queries is an object
        if (_.isObject(this.queries)) {

            if(_.isFunction(this.queries)){
                matchQueries = this.queries(queries);
            }else {
                // Make sure that you have an equal number of keys. We are
                // looping through the passed query params and not the expected values
                // if the user passes fewer query params than expected but all values
                // match this will throw a false positive. Testing that the length of the
                // passed query params is equal to the length of expected keys will prevent
                // us from doing any value checking BEFORE we know if they have all the proper
                // params
                debug('this.queries: %j', this.queries);
                debug('queries: %j', queries);
                if (_.size(this.queries) !== _.size(queries)) {
                    matchQueries = false;
                } else {
                    var self = this;
                    _.forOwn(queries, function matchOneKeyVal(val, key) {
                        var expVal = self.queries[key];
                        var isMatch = true;
                        if (val === undefined || expVal === undefined) {
                        isMatch = false;
                    } else if (expVal instanceof RegExp) {
                      isMatch = common.matchStringOrRegexp(val, expVal);
                    } else if (_.isArray(expVal) || _.isObject(expVal)) {
                      isMatch = _.isEqual(val, expVal);
                    } else {
                      isMatch = common.matchStringOrRegexp(val, expVal);
                    }
                matchQueries = matchQueries && !!isMatch;
                });
                }
                debug('matchQueries: %j', matchQueries);
            }
        }

        // Remove the query string from the path
        path = path.substr(0, queryIndex);
    }

    if (typeof this.uri === 'function') {
        matches = matchQueries &&
        method.toUpperCase() + ' ' + proto + '://' + options.host === this.baseUri &&
        this.uri.call(this, path);
    } else {
        matches = method === this.method &&
        common.matchStringOrRegexp(matchKey, this.basePath) &&
        common.matchStringOrRegexp(path, this.path) &&
        matchQueries;
    }

    // special logger for query()
    if (queryIndex !== -1) {
        this.scope.logger('matching ' + matchKey + '?' + queryString + ' to ' + this._key +
        ' with query(' + stringify(this.queries) + '): ' + matches);
    } else {
        this.scope.logger('matching ' + matchKey + ' to ' + this._key + ': ' + matches);
    }

    if (matches) {
        matches = (matchBody.call(options, this._requestBody, body));
        if (!matches) {
            this.scope.logger('bodies don\'t match: \n', this._requestBody, '\n', body);
        }
    }

    return matches;
};
Example #14
0
export function checkIsFunction(target: any, errorMessage: string) {
  if (!target || !_.isFunction(target)) {
    throw new Error(errorMessage);
  }
}
Example #15
0
 it('should create an getScale function on the xAxis class', function () {
   expect(_.isFunction(xAxis.getScale())).to.be(true);
 });
exports.execComposite = function execComposite(params) {
	var self = this,
		arg = params.arg,
		next = params.next;

	if (_.isFunction(arg)) {
		next = arg;
		arg = undefined;
	}

	var joinMeta = params.Model.getMeta('left_join') || params.Model.getMeta('inner_join'),
		modelMetas = {},
		isInnerJoin = !params.Model.getMeta('left_join'),
		modelMap = {},
		joinedModels = [],
		instances = {};

	if (_.isArray(joinMeta)) {
		for (var i = 0; i < joinMeta.length; i++) {
			modelMetas[joinMeta[i].model] = joinMeta[i];
		}
	}
	else if (joinMeta) {
		modelMetas[joinMeta.model] = joinMeta;
	}

	for (var fieldName in params.Model.fields) {
		/* istanbul ignore else */
		if (params.Model.fields.hasOwnProperty(fieldName)) {
			var field = params.Model.fields[fieldName],
				modelName = field.model,
				modelMeta = modelMetas[modelName];

			// Check the model.
			if (!modelName) {
				continue;
			}

			var GrabbedModel = Arrow.getModel(modelName);
			if (!GrabbedModel) {
				return next(new Error('Unable to find model ' + modelName + '.'));
			}

			// Check the field.
			if (modelMeta) {
				if (params.isWrite && (arg.getChangedFields ? arg.getChangedFields() : arg)[fieldName]) {
					return next(new Error('API-354: Joined fields cannot be written to yet.'));
				}
				if (params.method === 'query' && self.containsKey(arg, fieldName, ['sel', 'unsel'])) {
					return next(new Error('API-354: Joined fields cannot be queried on yet.'));
				}
			}

			// Map the model.
			if (modelMap[modelName]) {
				continue;
			}
			modelMap[modelName] = true;
			if (modelMeta) {
				joinedModels.push({
					name: modelName,
					readonly: true,
					left_join: modelMeta.join_properties,
					multiple: field.type === 'array' || field.type === Array,
					fieldName: fieldName
				});
			}
			else {
				joinedModels.unshift({
					name: modelName
				});
			}
		}
	}

	async.each(joinedModels, function modelExecHandler(model, cb) {
		if (params.isWrite && model.readonly) {
			return cb();
		}
		if (model.left_join || !model.name) {
			return cb();
		}
		var fieldKey = self.fetchModelObjectFieldKey(params.Model, model),
			localArg = arg;
		if (localArg && fieldKey) {
			localArg = localArg[fieldKey] || (localArg.where && localArg.where[fieldKey]) || localArg;
			localArg = self.checkParse(localArg, false);
		}
		if (params.isWrite && !localArg.getPrimaryKey) {
			localArg = _.pick(localArg, _.keys(Arrow.getModel(model.name).fields));
		}
		self.execModelMethod(params.Model, model, params.method, localArg, function methodCallback(err, instance) {
			if (err) {
				cb(err);
			}
			else {
				instances[model.name] = instance;
				cb();
			}
		});
	}, function modelsDoneCallback(err) {
		if (err) {
			next(err);
		}
		else {
			self.runJoin(params.Model, params.isCollection, instances, joinedModels, isInnerJoin, next);
		}
	});

};
Example #17
0
 it('should be a function', function () {
   expect(_.isFunction(xAxis.draw())).to.be(true);
 });
      y,
      verticalAnchor: labelStyle.verticalAnchor || verticalAnchor,
      textAnchor: labelStyle.textAnchor || "middle",
      angle: labelStyle.angle || angle,
      style: labelStyle,
      text: props.label
    };
  },

  getTicks(props, scale) {
    if (props.tickValues) {
      if (Axis.stringTicks(props)) {
        return range(1, props.tickValues.length + 1);
      }
      return props.tickValues;
    } else if (scale.ticks && isFunction(scale.ticks)) {
      const ticks = scale.ticks(props.tickCount);
      if (props.crossAxis) {
        return includes(ticks, 0) ? without(ticks, 0) : ticks;
      }
      return ticks;
    }
    return scale.domain();
  },

  getAnchors(orientation, isVertical) {
    const anchorOrientation = { top: "end", left: "end", right: "start", bottom: "start" };
    const anchor = anchorOrientation[orientation];
    return {
      textAnchor: isVertical ? anchor : "middle",
      verticalAnchor: isVertical ? "middle" : anchor
Example #19
0
    return function cache(req, res, next) {
      var cached;

      if (!globalOptions.enabled || req.headers['x-apicache-bypass'] || (_.isFunction(middlewareToggle) && !middlewareToggle(req, res))) {
        if (globalOptions.debug && req.headers['x-apicache-bypass']) {
          console.log('[api-cache]: bypass detected, skipping cache.');
        }
        return next();
      }
      // In Express 4.x the url is ambigious based on where a router is mounted.  originalUrl will give the full Url
      var key = req.originalUrl || req.url;
      
      // Remove querystring from key if jsonp option is enabled
      if (globalOptions.jsonp) {
        key = url.parse(key).pathname;
      }

      if (globalOptions.appendKey.length > 0) {
        var appendKey = req;

        for (var i = 0; i < globalOptions.appendKey.length; i++) {
          appendKey = appendKey[globalOptions.appendKey[i]];
        }
        key += '/appendKey=' + appendKey;
      }

      if (!globalOptions.redisClient) {
        cached = memCache.get(key);
      }

      if (cached || globalOptions.redisClient) {

        if (!globalOptions.redisClient) {

          if (globalOptions.debug) {
            console.log('[api-cache]: returning memCached version of "' + key + '"');
          }

          res.statusCode = cached.status;
          res.set(cached.headers);

          if(globalOptions.jsonp) {
            return res.jsonp(cached.body);
          }
          return res.send(cached.body);

        } else {

          if (globalOptions.debug) {
            console.log('[api-cache]: returning redis cached version of "' + key + '"');
          }

          globalOptions.redisClient.hgetall(key, function (err, obj) {
            //var redis_duration = obj.duration || globalOptions.defaultDuration;
            if(err){
              if (globalOptions.debug) {
                console.log('[api-cache] [redis-error]: ' + err);
              }
            }
            if(!obj){
              buildCacheObj();
            }else{
              if(obj.responseObj){

                var redis_responseObj = JSON.parse(obj.responseObj);
                res.statusCode = redis_responseObj.status;
                res.set(JSON.stringify(redis_responseObj.headers));
                return res.send(redis_responseObj.body);
              }else{
                buildCacheObj();
              }
            }
          });

        }

      } else {
        buildCacheObj();
      }

      function buildCacheObj() {
        if (globalOptions.debug) {
          console.log('[api-cache]: path "' + key + '" not found in cache');
        }

        res.realSend = (globalOptions.jsonp) ? res.jsonp : res.send;
        
        var methodName = (globalOptions.jsonp) ? "jsonp" : "send";
        
        res[methodName] = function(a, b) {
          var responseObj = {
            headers: {
              'Content-Type': 'text/html; charset=utf-8'
            }
          };

          responseObj.status  = !_.isUndefined(b) ? a : (_.isNumber(a) ? a : res.statusCode);
          responseObj.body    = !_.isUndefined(b) ? b : (!_.isNumber(a) ? a : null);

          // last bypass attempt
          if (!memCache.get(key) && !req.headers['x-apicache-bypass']) {
            if (req.apicacheGroup) {
              if (globalOptions.debug) {
                console.log('[api-cache]: group detected: ' + req.apicacheGroup);
              }
              index.groups[req.apicacheGroup] = index.groups[req.apicacheGroup] || [];
              index.groups[req.apicacheGroup].push(key);
            }

            index.all.push(key);
            
            if (globalOptions.debug) {
              console.log('[api-cache]: adding cache entry for "' + key + '" @ ' + duration + ' milliseconds');
            }

            _.each(['Cache-Control', 'Expires'], function(h) {
              var header = res.get(h);
              if (!_.isUndefined(header)) {
                responseObj.headers[h] = header;
              }
            });

            if (!globalOptions.redisClient) {
              memCache.put(key, responseObj, duration);
            } else {
              globalOptions.redisClient.hset(key, "responseObj", JSON.stringify(responseObj));
              globalOptions.redisClient.hset(key, "duration", duration);
            }
          }

          return res.realSend(responseObj.body);
        };
        next();
      }
    };
Example #20
0
           }
           return val;
       }, indent || 4);
   },

    fileExistsSync(path) {
       try {
           fs.accessSync(path, fs.F_OK);
           return true;
       } catch (e) {
           return false;
       }
   },

    isPromise(value) {
       return (value && _.isFunction(value.then));
   },

    md5(str) {
       return crypto.createHash('md5').update(str).digest('hex');
   },

    mergeProp(prop, upstream) {
        if (_.isFunction(prop)) {
            return prop;
        }
        if (_.isFunction(upstream)) {
            return upstream;
        }
        if (_.isArray(upstream)) {
            return _.uniq(_.concat(upstream, _.castArray(prop)));
	criteria: function normalizeCriteria(origCriteria) {
		var criteria = _.clone(origCriteria);

		if(!criteria) return {
			where: null
		};

		// Empty undefined values from criteria object
		_.each(criteria, function(val, key) {
			if(_.isUndefined(val)) delete criteria[key];
		});

		// Convert non-objects (ids) into a criteria
		// TODO: use customizable primary key attribute
		if(!_.isObject(criteria)) {
			criteria = {
				id: +criteria || criteria
			};
		}

		// Return string to indicate an error
		if(!_.isObject(criteria)) throw new Error('Invalid options/criteria :: ' + criteria);

		// If criteria doesn't seem to contain operational keys, assume all the keys are criteria
		if(!criteria.where && !criteria.limit && !criteria.skip && !criteria.sort) {

			// Delete any residuals and then use the remaining keys as attributes in a criteria query
			delete criteria.where;
			delete criteria.limit;
			delete criteria.skip;
			delete criteria.skip;
			criteria = {
				where: criteria
			};
		}
		// If where is null, turn it into an object
		else if(_.isNull(criteria.where)) criteria.where = {};

		// If WHERE is {}, always change it back to null
		if(criteria.where && _.keys(criteria.where).length === 0) {
			criteria.where = null;
		}

		// If a LIKE was specified, normalize it
		if(criteria.where && criteria.where.like) {
			_.each(criteria.where.like, function(criterion, attrName) {
				criteria.where.like[attrName] = normalizePercentSigns(criterion);
			});
		}

		// Normalize sort criteria
		if(criteria.sort) {
			// Split string into attr and sortDirection parts (default to 'asc')
			if(_.isString(criteria.sort)) {
				var parts = _.str.words(criteria.sort);
				parts[1] = parts[1] ? parts[1].toLowerCase() : 'asc';
				if(parts.length !== 2 || (parts[1] !== 'asc' && parts[1] !== 'desc')) {
					throw new Error('Invalid sort criteria :: ' + criteria.sort);
				}
				criteria.sort = {};
				criteria.sort[parts[0]] = (parts[1] === 'asc') ? 1 : -1;
			}

			// Verify that user either specified a proper object
			// or provided explicit comparator function
			if(!_.isObject(criteria.sort) && !_.isFunction(criteria.sort)) {
				throw new Error('Invalid sort criteria for ' + attrName + ' :: ' + direction);
			}
		}

		return criteria;
	},
Example #22
0
 it('should be a function', function () {
   expect(_.isFunction(Data)).to.be(true);
 });
Example #23
0
keystone.Email.prototype.send = function (options, callback) {

	// create transport once
	if (!transport) {
		transport = nodemailer.createTransport(keystone.get('email nodemailer'));
	}

	var locals = options;

	var prepareOptions = [locals];

	if (arguments.length === 3 ) {
		// we expect locals, options, callback
		if (_.isObject(arguments[1])) {
			prepareOptions.push(arguments[1]);
		}
		callback = arguments[2];

	} else if (arguments.length === 2 && !_.isFunction(callback)) {
		// no callback so we expect locals, options
		if (_.isObject(arguments[1])) {
			prepareOptions.push(arguments[1]);
		}
		callback = function(err, info) {// eslint-disable-line no-unused-vars
			if (err) console.log(err);
		};

	} else if (arguments.length === 1) {
		// we expect options here and it is pushed already
		callback = function(err, info){// eslint-disable-line no-unused-vars
			if (err) console.log(err);
		};
	}

	prepareOptions.push(function(err, toSend) {

		if (err) {
			return callback(err, null);
		}

		return process.nextTick(function() {
			var message = toSend.message;

			var attachments = [];
			async.each(message.attachments,(el, callback)=>{
				console.log(el);
				attachments.push({
					cid: attachment.cid,
					filename: attachment.name,
					content: attachment.content,
					contentType: attachment.type,
					encoding: 'base64'
				});
				callback();
			}, ()=> {
				console.log(attachments);
				var mail = {
					from: buildAddress(message.from_email, message.from_name),
					to: message.to.map(function (to) {
						return buildAddress(to.email, to.name)
					}).join(', '),
					subject: message.subject,
					html: message.html,
					attachments: attachments
				};

				if (options.sendPlainText) {
					if (typeof options.sendPlainText === 'object') {
						mail.text = htmlToText.fromString(message.html, options.sendPlainText);
					} else {
						mail.text = htmlToText.fromString(message.html);
					}
				}

				transport.sendMail(mail, function(error, info) {
					if (error) {
						callback({
							from: 'Email.send',
							key: 'send error',
							message: 'Nodemailer encountered an error and did not send the emails.',
							info: info
						});
					} else {
						callback(null, info);
					}
				});
			});


		});

	}.bind(this));

	this.prepare.apply(this, prepareOptions);

};
Example #24
0
 it('should return a Vis function', function () {
   expect(_.isFunction(vislib.Vis)).to.be(true);
 });
Example #25
0
 $scope.canMoveColumnLeft = function canMoveColumn(columnName) {
   return (
     _.isFunction($scope.onMoveColumn)
     && $scope.columns.indexOf(columnName) > 0
   );
 };
Example #26
0
var httpProxyMiddleware = function(context, opts) {
    var isWsUpgradeListened = false;
    var config              = configFactory.createConfig(context, opts);
    var proxyOptions        = config.options;

    // create proxy
    var proxy = httpProxy.createProxyServer(proxyOptions);
    logger.info('[HPM] Proxy created:', config.context, ' -> ', proxyOptions.target);

    var pathRewriter = PathRewriter.create(proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided

    // Custom listener for the `proxyRes` event on `proxy`.
    if (_.isFunction(proxyOptions.onProxyRes)) {
        proxy.on('proxyRes', proxyOptions.onProxyRes);
    }

    // Custom listener for the `proxyReq` event on `proxy`.
    if (_.isFunction(proxyOptions.onProxyReq)) {
        proxy.on('proxyReq', proxyOptions.onProxyReq);
    }

    // Custom listener for the `error` event on `proxy`.
    var onProxyError = getProxyErrorHandler();
    // handle error and close connection properly
    proxy.on('error', onProxyError);
    proxy.on('error', proxyErrorLogger);

    // Listen for the `close` event on `proxy`.
    proxy.on('close', function(req, socket, head) {
        // view disconnected websocket connections
        logger.info('[HPM] Client disconnected');
    });

    // https://github.com/chimurai/http-proxy-middleware/issues/19
    // expose function to upgrade externally
    middleware.upgrade = function(req, socket, head) {
        handleUpgrade(req, socket, head);
        isWsUpgradeListened = true;
    };

    return middleware;

    function middleware(req, res, next) {
        // https://github.com/chimurai/http-proxy-middleware/issues/17
        if (req.baseUrl) {
            req.url = req.originalUrl;
        }

        if (contextMatcher.match(config.context, req.url)) {
            var activeProxyOptions = prepareProxyRequest(req);
            proxy.web(req, res, activeProxyOptions);
        } else {
            next();
        }

        if (proxyOptions.ws === true) {
            catchUpgradeRequest(req.connection.server);
        }
    }

    function catchUpgradeRequest(server) {
        // make sure only 1 handle listens to server's upgrade request.
        if (isWsUpgradeListened === true) {
            return;
        }

        server.on('upgrade', handleUpgrade);
        isWsUpgradeListened = true;
    }

    function handleUpgrade(req, socket, head) {
        if (contextMatcher.match(config.context, req.url)) {
            var activeProxyOptions = prepareProxyRequest(req);
            proxy.ws(req, socket, head, activeProxyOptions);
            logger.info('[HPM] Upgrading to WebSocket');
        }
    }

    /**
     * Apply option.proxyTable and option.pathRewrite
     * Order matters:
          ProxyTable uses original path for routing;
          NOT the modified path, after it has been rewritten by pathRewrite
     */
    function prepareProxyRequest(req) {
        // store uri before it gets rewritten for logging
        var originalPath = req.url;

        // apply apply option.proxyTable & option.pathRewrite
        var alteredProxyOptions = __applyProxyTableOption(req, proxyOptions);
        __applyPathRewrite(req, pathRewriter);

        // debug logging for both http(s) and websockets
        if (proxyOptions.logLevel === 'debug') {
            var arrow = getArrow(originalPath, req.url, proxyOptions.target, alteredProxyOptions.target);
            logger.debug('[HPM] %s %s %s %s', req.method, originalPath, arrow, alteredProxyOptions.target);
        }

        return alteredProxyOptions;
    }

    // Modify option.target when proxyTable present.
    // return altered options
    function __applyProxyTableOption(req) {
        var result = proxyOptions;

        if (proxyOptions.proxyTable) {
            result = ProxyTable.createProxyOptions(req, proxyOptions);
        }

        return result;
    }

    // rewrite path
    function __applyPathRewrite(req) {
        if (pathRewriter) {
            req.url = pathRewriter(req.url);
        }
    }

    function getProxyErrorHandler() {
        if (_.isFunction(proxyOptions.onError)) {
            return proxyOptions.onError;   // custom error listener
        }

        return handlers.proxyError;       // otherwise fall back to default
    }

    function proxyErrorLogger(err, req, res) {
        var hostname = (req.hostname || req.host) || (req.headers && req.headers.host); // (node0.10 || node 4/5) || (websocket)
        var targetUri = (proxyOptions.target.host || proxyOptions.target) + req.url;

        logger.error('[HPM] PROXY ERROR: %s. %s -> %s', err.code, hostname, targetUri);
    }

};
Example #27
0
 $scope.canRemoveColumn = function canRemoveColumn(columnName) {
   return (
     _.isFunction($scope.onRemoveColumn)
     && (columnName !== '_source' || $scope.columns.length > 1)
   );
 };
Example #28
0
 it('should return a function', function () {
   expect(_.isFunction(xScale)).to.be(true);
 });
Example #29
0
 _.forOwn(this, function(value, key) {
   if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
     clone[key] = value;
   }
 });
Example #30
0
var Connection = function(opts) {
  var self = this;

  opts = _.defaults(opts || {}, {
    clientId:      null,
    clientSecret:  null,
    redirectUri:   null,
    loginUri:      LOGIN_URI,
    testLoginUri:  TEST_LOGIN_URI,
    cacheMetadata: false,
    apiVersion:    _.last(API_VERSIONS),
    environment:   'production',
    mode:          'multi',
    gzip:          false,
    autoRefresh:   false,
    onRefresh:     undefined,
    timeout:       undefined
  });

  // convert option values

  opts.apiVersion = opts.apiVersion.toString().toLowerCase().replace('v', '').replace('\.0', '');
  opts.environment = opts.environment.toLowerCase();
  opts.mode = opts.mode.toLowerCase();

  self = _.assign(this, opts);

  // validate options

  if(!_.isString(this.clientId)) throw new Error('invalid or missing clientId');
  if(!_.isString(this.redirectUri)) throw new Error('invalid or missing redirectUri');
  if(!_.isString(this.loginUri)) throw new Error('invalid or missing loginUri');
  if(!_.isString(this.testLoginUri)) throw new Error('invalid or missing testLoginUri');
  if(!_.isBoolean(this.cacheMetadata)) throw new Error('cacheMetadata must be a boolean');
  if(!_.isBoolean(this.gzip)) throw new Error('gzip must be a boolean');
  if(!_.isString(this.environment) || _.indexOf(ENVS, this.environment) === -1) {
    throw new Error('invalid environment, only ' + ENVS.join(' and ') + ' are allowed');
  }
  if(!_.isString(this.mode) || _.indexOf(MODES, this.mode) === -1) {
    throw new Error('invalid mode, only ' + MODES.join(' and ') + ' are allowed');
  }
  if(this.onRefresh && !_.isFunction(this.onRefresh)) throw new Error('onRefresh must be a function');
  if(this.timeout && !_.isNumber(this.timeout)) throw new Error('timeout must be a number');

  // setup cache

  if(this.cacheMetadata) {
    this._cache = {
      keyPrefixes: {},
      sObjects: {}
    }
  }

  // parse api version

  try {
    this.apiVersion = 'v' + parseInt(this.apiVersion, 10) + '.0';
  } catch (err) {
    throw new Error('invalid apiVersion number');
  }
  if(API_VERSIONS.indexOf(this.apiVersion) === -1) {
    throw new Error('api version ' + this.apiVersion + ' is not supported');
  }

  // parse timeout into integer in case it's a floating point.

  this.timeout = parseInt(this.timeout, 10);

  // load plugins

  if(opts.plugins && _.isArray(opts.plugins)) {
    opts.plugins.forEach(function(pname) {
      if(!plugins[pname]) throw new Error('plugin ' + pname + ' not found');
      // clone the object
      self[pname] = _.clone(plugins[pname]._fns);

      // now bind to the connection object
      _.forOwn(self[pname], function(fn, key) {
        self[pname][key] = _.bind(self[pname][key], self);
      });

    });
  }

}