use eslint autofix to start fixing violations

This commit is contained in:
spalger
2017-06-14 18:48:24 -07:00
parent da8e558817
commit 3d75c6ff0f
97 changed files with 1281 additions and 1280 deletions

View File

@ -13,4 +13,5 @@ rules:
no-use-before-define: warn
no-empty: warn
space-before-function-paren: warn
no-restricted-globals: warn
no-restricted-globals: warn
prefer-const: warn

View File

@ -1,14 +1,14 @@
var get = require('lodash.get');
var utils = require('../utils');
var fromRoot = require('path').join.bind(null, __dirname, '..', '..');
const get = require('lodash.get');
const utils = require('../utils');
const fromRoot = require('path').join.bind(null, __dirname, '..', '..');
var release = process.env.ES_RELEASE;
var ref = process.env.ES_REF;
var port = parseFloat(get(process.env, 'ES_PORT', 9400));
var host = get(process.env, 'ES_HOST', 'localhost');
const release = process.env.ES_RELEASE;
const ref = process.env.ES_REF;
const port = parseFloat(get(process.env, 'ES_PORT', 9400));
const host = get(process.env, 'ES_HOST', 'localhost');
var Version = require('../../scripts/Version');
var versionedOpts = [
const Version = require('../../scripts/Version');
const versionedOpts = [
{
version: '*',
directory: fromRoot('esvm'),
@ -90,8 +90,8 @@ utils.branches.forEach(function (branch) {
// ci target, based on env variables
(function () {
var v;
var opts = {
let v;
const opts = {
config: {
'http.port': port
}

View File

@ -1,12 +1,12 @@
var root = require('find-root')(__dirname);
var rel = require('path').resolve.bind(null, root);
var rootReq = function (p) { return require(rel(p)); };
var _ = rootReq('src/lib/utils');
var grunt = require('grunt');
const root = require('find-root')(__dirname);
const rel = require('path').resolve.bind(null, root);
const rootReq = function (p) { return require(rel(p)); };
const _ = rootReq('src/lib/utils');
const grunt = require('grunt');
var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js');
const JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js');
var config = {
const config = {
unit: {
src: 'test/unit/index.js',
options: {

View File

@ -1,6 +1,6 @@
var utils = require('../utils');
const utils = require('../utils');
var config = {
const config = {
generate: {
exec: 'node ./scripts/generate/index.js',
options: {

View File

@ -1,4 +1,4 @@
var config = {};
let config = {};
try {
config = require('../../.aws-config.json');
} catch (e) {}

View File

@ -1,4 +1,4 @@
var slk = require('../../test/utils/slk');
const slk = require('../../test/utils/slk');
module.exports = {
all: {
options: {

View File

@ -4,4 +4,4 @@ module.exports = {
require('../../webpack_config/angular'),
require('../../webpack_config/jquery'),
]
}
};

View File

@ -1,8 +1,8 @@
module.exports = function (grunt) {
var Promise = require('bluebird');
var utils = require('./utils');
var readFile = Promise.promisify(require('fs').readFile);
var writeFile = Promise.promisify(require('fs').writeFile);
const Promise = require('bluebird');
const utils = require('./utils');
const readFile = Promise.promisify(require('fs').readFile);
const writeFile = Promise.promisify(require('fs').writeFile);
// Default task runs the build process.
@ -11,12 +11,12 @@ module.exports = function (grunt) {
]);
grunt.registerTask('test', function (branch) {
var tasks = [
const tasks = [
branch ? 'run:generate_' + branch : 'run:generate',
'mochacov:unit'
];
var branches = branch ? [branch] : utils.branches;
const branches = branch ? [branch] : utils.branches;
process.env.ES_PORT = process.env.ES_PORT || 9400;
process.env.ES_HOST = process.env.ES_HOST || 'localhost';
@ -38,10 +38,10 @@ module.exports = function (grunt) {
]);
grunt.registerTask('version', function (nextVersion) {
var root = require('path').join.bind(null, __dirname, '..');
var readmePath = root('README.md');
var packagePath = root('package.json');
var browserBuildsPath = root('docs/browser_builds.asciidoc');
const root = require('path').join.bind(null, __dirname, '..');
const readmePath = root('README.md');
const packagePath = root('package.json');
const browserBuildsPath = root('docs/browser_builds.asciidoc');
Promise.all([
require(packagePath),
@ -49,7 +49,7 @@ module.exports = function (grunt) {
readFile(browserBuildsPath, 'utf8')
])
.spread(function (pkg, readme, browserBuilds) {
var current = pkg.version;
const current = pkg.version;
pkg.version = nextVersion;
browserBuilds = utils.replaceAll(browserBuilds, current, nextVersion);

View File

@ -1,10 +1,10 @@
var _ = require('../src/lib/utils');
const _ = require('../src/lib/utils');
var root = require('find-root')(__dirname);
var pkg = require(root + '/package.json');
var stable = pkg.config.supported_es_branches;
var unstable = pkg.config.unstable_es_branches;
var branches = [].concat(stable, unstable);
const root = require('find-root')(__dirname);
const pkg = require(root + '/package.json');
const stable = pkg.config.supported_es_branches;
const unstable = pkg.config.unstable_es_branches;
const branches = [].concat(stable, unstable);
var utils = {
branchSuffix: function (branch) {
@ -29,7 +29,7 @@ utils.minorVersion = function (version) {
* increment the version based on the release "type"
*/
utils.increaseVersion = function (version, type) {
var i;
let i;
switch (type) {
case 'major':
i = 0;
@ -47,14 +47,14 @@ utils.increaseVersion = function (version, type) {
}
// breakout the current version
var next = version.split('.').map(function (n) {
const next = version.split('.').map(function (n) {
return parseInt(n, 10);
});
// increment the version type
next[i] += 1;
// clear out all following numbers
for (i ++; i < next.length; i++) next[i] = 0;
for (i++; i < next.length; i++) next[i] = 0;
// join back together with '.'
return next.join('.');
};
@ -63,9 +63,9 @@ utils.increaseVersion = function (version, type) {
* replace all instances of `replace` with `replacement` without creating a regexp object
*/
utils.replaceAll = function (str, replace, replacement) {
var out = '';
var remaining = str;
var i = 0;
let out = '';
let remaining = str;
let i = 0;
while (~(i = remaining.indexOf(replace))) {
out += remaining.substring(0, i) + replacement;

View File

@ -1,16 +1,16 @@
var _ = require('lodash');
var pkg = require('../package.json');
var branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches];
var semver = require('semver');
const _ = require('lodash');
const pkg = require('../package.json');
const branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches];
const semver = require('semver');
function nextMajorVersion() {
const largestMajor = branches
.map(v => parseFloat(v.split('.')[0]))
.filter(n => !isNaN(n))
.sort((a, b) => b - a)
.shift()
.shift();
return new Version(`${largestMajor + 1}.0.0`)
return new Version(`${largestMajor + 1}.0.0`);
}
function nextMinorVersion(major) {
@ -42,11 +42,11 @@ Version.fromBranch = function (branch) {
if (/^\d+\.\d+$/.test(branch)) return new Version(branch + '.0');
// n.x -> n.(maxVersion + 1).0
const match = branch.match(/^(\d+)\.x$/i)
const match = branch.match(/^(\d+)\.x$/i);
if (match) return nextMinorVersion(match[1]);
// master => (maxMajorVersion + 1).0.0
if (branch === 'master') return nextMajorVersion()
if (branch === 'master') return nextMajorVersion();
throw new Error('unable to convert branch "' + branch + '" to semver');
};
@ -66,9 +66,9 @@ Version.prototype.mergeOpts = function (versioned, overrides) {
const candidates = versioned
.filter(o => this.satisfies(o.version))
.map(o => _.omit(o, 'version'))
.map(o => _.omit(o, 'version'));
return _.merge({}, overrides || {}, ...candidates)
return _.merge({}, overrides || {}, ...candidates);
};
module.exports = Version;

View File

@ -1,11 +1,11 @@
module.exports = _spawn;
var map = require('through2-map');
var split = require('split');
var chalk = require('chalk');
var spawn = require('child_process').spawn;
var path = require('path');
var root = path.resolve(__dirname, '../');
const map = require('through2-map');
const split = require('split');
const chalk = require('chalk');
const spawn = require('child_process').spawn;
const path = require('path');
const root = path.resolve(__dirname, '../');
function indent(line) {
line = String(line).trim();
@ -26,7 +26,7 @@ function _spawn(cmd, args, opts, cb) {
opts.verbose = false;
}
var conf = {
const conf = {
stdio: [
'ignore',
opts.verbose ? 'pipe' : 'ignore',
@ -34,7 +34,7 @@ function _spawn(cmd, args, opts, cb) {
]
};
var subdir;
let subdir;
if (opts.cwd) {
conf.cwd = opts.cwd;
@ -43,7 +43,7 @@ function _spawn(cmd, args, opts, cb) {
console.log(chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + cmd + ' ' + args.join(' '));
var cp = spawn(cmd, args, conf);
const cp = spawn(cmd, args, conf);
if (opts.verbose) {
consume(cp.stdout);

View File

@ -17,25 +17,25 @@
*
*******/
var Promise = require('bluebird');
var _ = require('lodash');
var through2 = require('through2');
var map = require('through2-map');
var split = require('split');
var join = require('path').join;
var cp = require('child_process');
var chalk = require('chalk');
var format = require('util').format;
const Promise = require('bluebird');
const _ = require('lodash');
const through2 = require('through2');
const map = require('through2-map');
const split = require('split');
const join = require('path').join;
const cp = require('child_process');
const chalk = require('chalk');
const format = require('util').format;
var NL_RE = /(\r?\n)/g;
var ROOT = join(__dirname, '..');
var GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt');
var ENV = _.clone(process.env);
var JENKINS = !!ENV.JENKINS_HOME;
var TASKS = [];
const NL_RE = /(\r?\n)/g;
const ROOT = join(__dirname, '..');
const GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt');
const ENV = _.clone(process.env);
const JENKINS = !!ENV.JENKINS_HOME;
const TASKS = [];
var output; // main output stream
var taskOut; // task output stream
let output; // main output stream
let taskOut; // task output stream
task('NODE_UNIT', true, function () {
if (!JENKINS) {
@ -46,11 +46,11 @@ task('NODE_UNIT', true, function () {
});
task('NODE_INTEGRATION', true, function () {
var branch = ENV.ES_REF;
const branch = ENV.ES_REF;
return node('scripts/generate', '--no-api', '--branch', branch)
.then(function () {
var target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch;
const target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch;
return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env');
});
});
@ -58,9 +58,9 @@ task('NODE_INTEGRATION', true, function () {
task('SAUCE_LABS', false, function () {
return new Promise(function (resolve, reject) {
// build the clients and start the server, once the server is ready call trySaucelabs()
var serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive'];
const serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive'];
spawn(GRUNT, serverTasks, function (proc) {
var toLines = split();
const toLines = split();
proc.stdout
.pipe(toLines)
@ -83,14 +83,14 @@ task('SAUCE_LABS', false, function () {
.catch(_.noop);
// attempt to run tests on saucelabs and retry if it fails
var saucelabsAttempts = 0;
let saucelabsAttempts = 0;
function trySaucelabs() {
saucelabsAttempts++;
return new Promise(function (resolve, reject) {
log(chalk.green('saucelabs attempt #', saucelabsAttempts));
spawn(GRUNT, ['saucelabs-mocha'], function (cp) {
var failedTests = 0;
let failedTests = 0;
cp.stdout
.pipe(split())
.pipe(map(function (line) {
@ -141,7 +141,7 @@ execTask('SETUP', function () {
}
}
var match;
let match;
if (match = ENV.ES_V.match(/^(.*)_nightly$/)) {
return [match[1], null];
}
@ -206,7 +206,7 @@ execTask('SETUP', function () {
* utils
******/
function log() {
var chunk = format.apply(null, arguments);
const chunk = format.apply(null, arguments);
(taskOut || output || process.stdout).write(chunk + '\n');
}
@ -218,15 +218,15 @@ function logImportant(text) {
function push(m) {
return function () {
var args = _.toArray(arguments);
var cb = args.pop();
const args = _.toArray(arguments);
const cb = args.pop();
this.push(m.apply(this, args));
cb();
};
}
function indent() {
var str = through2(
const str = through2(
push(function (chunk) { return String(chunk).replace(NL_RE, '$1 '); }),
push(function () { return '\n'; })
);
@ -281,7 +281,7 @@ function execTask(name, task) {
function spawn(file, args, block) {
return new Promise(function (resolve, reject) {
var proc = cp.spawn(file, args, {
const proc = cp.spawn(file, args, {
cwd: ROOT,
env: ENV,
stdio: [0, 'pipe', 'pipe']
@ -290,7 +290,7 @@ function spawn(file, args, block) {
proc.stdout.pipe(taskOut, { end: false });
proc.stderr.pipe(taskOut, { end: false });
var stdout = '';
let stdout = '';
proc.stdout
.pipe(through2(function (chunk, enc, cb) {
stdout += chunk;

View File

@ -1,13 +1,13 @@
module.exports = function (done) {
var _ = require('../../src/lib/utils');
var utils = require('../../grunt/utils');
const _ = require('../../src/lib/utils');
const utils = require('../../grunt/utils');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var write = require('fs').writeFileSync;
const chalk = require('chalk');
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
const write = require('fs').writeFileSync;
var nodeApiIndex = fromRoot('src/lib/apis/index.js');
var browserApiIndex = fromRoot('src/lib/apis/browser_index.js');
const nodeApiIndex = fromRoot('src/lib/apis/index.js');
const browserApiIndex = fromRoot('src/lib/apis/browser_index.js');
write(nodeApiIndex, require('./templates').apiIndex({
branches: utils.branches

View File

@ -1,11 +1,11 @@
module.exports = function (done) {
var _ = require('../../src/lib/utils');
const _ = require('../../src/lib/utils');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var write = require('fs').writeFile;
const chalk = require('chalk');
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
const write = require('fs').writeFile;
var outputPath = fromRoot('docs/configuration.asciidoc');
const outputPath = fromRoot('docs/configuration.asciidoc');
write(outputPath, require('./templates').configurationDocs(), 'utf8', done);
console.log(chalk.white.bold('wrote'), 'configuration docs to', outputPath);
};

View File

@ -1,12 +1,12 @@
module.exports = function (done) {
var _ = require('../../src/lib/utils');
var utils = require('../../grunt/utils');
const _ = require('../../src/lib/utils');
const utils = require('../../grunt/utils');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var write = require('fs').writeFile;
const chalk = require('chalk');
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
const write = require('fs').writeFile;
var outputPath = fromRoot('docs/index.asciidoc');
const outputPath = fromRoot('docs/index.asciidoc');
write(outputPath, require('./templates').docsIndex({
apiFiles: utils.stableBranches.map(function (branch) {

View File

@ -1,8 +1,8 @@
/* jshint curly: false */
var async = require('async');
var fs = require('fs');
var spawn = require('../_spawn');
var argv = require('optimist')
const async = require('async');
const fs = require('fs');
const spawn = require('../_spawn');
let argv = require('optimist')
.options({
verbose: {
alias: 'v',
@ -27,15 +27,15 @@ var argv = require('optimist')
}
});
var path = require('path');
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
var utils = require(fromRoot('grunt/utils'));
var _ = require(fromRoot('src/lib/utils'));
var esUrl = process.env.ES_REPO
const path = require('path');
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
const utils = require(fromRoot('grunt/utils'));
const _ = require(fromRoot('src/lib/utils'));
const esUrl = process.env.ES_REPO
? path.resolve(process.cwd(), process.env.ES_REPO)
: 'https://github.com/elastic/elasticsearch.git';
var branches;
let branches;
if (process.env.npm_config_argv) {
// when called by NPM
@ -51,7 +51,7 @@ if (argv.branch) {
branches = utils.branches;
}
var paths = {
const paths = {
root: fromRoot('.'),
src: fromRoot('src'),
esSrc: fromRoot('src/_elasticsearch_'),
@ -70,7 +70,7 @@ var paths = {
};
function isDirectory(dir) {
var stat;
let stat;
try { stat = fs.statSync(dir); } catch (e) {}
return (stat && stat.isDirectory());
}
@ -129,15 +129,15 @@ function initStep() {
}
function fetchBranchesStep() {
var branchArgs = branches.map(function (b) { return b + ':' + b; });
const branchArgs = branches.map(function (b) { return b + ':' + b; });
return spawnStep('git', ['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs), paths.esSrc);
}
function findGeneratedApiFiles() {
var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/;
var anyApiJsFiled = /^.+\.js$/;
var allBranches = _.isEqual(branches, utils.branches);
const anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/;
const anyApiJsFiled = /^.+\.js$/;
const allBranches = _.isEqual(branches, utils.branches);
if (allBranches) {
return [
@ -147,11 +147,11 @@ function findGeneratedApiFiles() {
}
return branches.reduce(function (files, branch) {
var b = _.snakeCase(branch);
const b = _.snakeCase(branch);
files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc'));
var isDefault = branch === utils.branches._default;
const isDefault = branch === utils.branches._default;
if (isDefault) {
files.push(dirOpts(paths.docs, 'api_methods.asciidoc'));
}
@ -164,8 +164,8 @@ function findGeneratedApiFiles() {
function clearGeneratedFiles() {
var esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/;
var generatedFiles = [];
const esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/;
const generatedFiles = [];
if (argv.api) {
generatedFiles.push(findGeneratedApiFiles());
@ -173,7 +173,7 @@ function clearGeneratedFiles() {
generatedFiles.push(dirRegex(paths.src, esArchives));
var rmSteps = _.chain(generatedFiles)
const rmSteps = _.chain(generatedFiles)
.flatten()
.uniq()
.map(function (path) {
@ -191,7 +191,7 @@ function clearGeneratedFiles() {
function removePrevArchive(branch) {
if (!argv.update) return;
var dir = paths.getArchiveDir(branch);
const dir = paths.getArchiveDir(branch);
if (!isDirectory(dir)) return;
return spawnStep('rm', ['-rf', dir], paths.root);
@ -199,10 +199,10 @@ function removePrevArchive(branch) {
function createArchive(branch) {
return function (done) {
var dir = paths.getArchiveDir(branch);
var tarball = paths.getArchiveTarball(branch);
var specPathInRepo = paths.getSpecPathInRepo(branch);
var subDirCount = _.countBy(specPathInRepo, p => p === '/').true || 0;
const dir = paths.getArchiveDir(branch);
const tarball = paths.getArchiveTarball(branch);
const specPathInRepo = paths.getSpecPathInRepo(branch);
const subDirCount = _.countBy(specPathInRepo, p => p === '/').true || 0;
if (isDirectory(dir)) {
console.log(branch + ' archive already exists');
@ -227,7 +227,7 @@ function generateStep(branch) {
};
}
var steps = [
const steps = [
initStep(),
clearGeneratedFiles(),
fetchBranchesStep()

View File

@ -3,26 +3,26 @@ module.exports = function (branch, done) {
* Read the API actions form the rest-api-spec repo.
* @type {[type]}
*/
var _ = require('../../src/lib/utils');
var utils = require('../../grunt/utils');
var fs = require('fs');
var async = require('async');
var chalk = require('chalk');
var path = require('path');
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
var templates = require('./templates');
var Version = require('../Version');
var urlParamRE = /\{(\w+)\}/g;
const _ = require('../../src/lib/utils');
const utils = require('../../grunt/utils');
const fs = require('fs');
const async = require('async');
const chalk = require('chalk');
const path = require('path');
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
const templates = require('./templates');
const Version = require('../Version');
const urlParamRE = /\{(\w+)\}/g;
var files; // populated in readSpecFiles
var apiSpec; // populated by parseSpecFiles
var docVars; // slightly modified clone of apiSpec for the docs
let files; // populated in readSpecFiles
let apiSpec; // populated by parseSpecFiles
let docVars; // slightly modified clone of apiSpec for the docs
var branchSuffix = utils.branchSuffix(branch);
var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
const branchSuffix = utils.branchSuffix(branch);
const esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
var version = Version.fromBranch(branch);
var overrides = version.mergeOpts(require('./overrides'), {
const version = Version.fromBranch(branch);
const overrides = version.mergeOpts(require('./overrides'), {
aliases: {},
mergeConcatParams: {},
paramAsBody: {},
@ -31,7 +31,7 @@ module.exports = function (branch, done) {
descriptions: {},
});
var steps = [
const steps = [
readSpecFiles,
parseSpecFiles,
writeApiFile
@ -51,13 +51,13 @@ module.exports = function (branch, done) {
});
function readSpecFiles(done) {
var apiDir = path.join(esDir, 'rest-api-spec/api/');
const apiDir = path.join(esDir, 'rest-api-spec/api/');
files = fs.readdirSync(apiDir)
.filter(function (filename) {
return filename[0] !== '_'
return filename[0] !== '_';
})
.map(function (filename) {
var module = require(apiDir + filename);
const module = require(apiDir + filename);
delete require.cache[apiDir + filename];
return module;
});
@ -65,7 +65,7 @@ module.exports = function (branch, done) {
}
function parseSpecFiles(done) {
var actions = [];
const actions = [];
files.forEach(function (spec) {
__puke__transformSpec(spec).forEach(function (action) {
@ -74,16 +74,16 @@ module.exports = function (branch, done) {
});
// collect the namespaces from the action locations
var namespaces = _.filter(_.map(actions, function (action) {
const namespaces = _.filter(_.map(actions, function (action) {
return action.location
.split('.')
.slice(0, -1)
.filter(step => step !== 'prototype')
.join('.prototype.')
.join('.prototype.');
}));
// seperate the proxy actions
var groups = _.groupBy(actions, function (action) {
const groups = _.groupBy(actions, function (action) {
return action.proxy ? 'proxies' : 'normal';
});
@ -95,7 +95,7 @@ module.exports = function (branch, done) {
};
if (!_.find(apiSpec.actions, { name: 'create' })) {
var create = _.assign(
const create = _.assign(
{},
_.cloneDeep(_.find(apiSpec.actions, { name: 'index' })),
{
@ -115,8 +115,8 @@ module.exports = function (branch, done) {
[].concat(apiSpec.actions, apiSpec.proxies)
.forEach(function (action) {
var examplePath = overrides.examples[action.name] || action.name + '.asciidoc';
var descriptionPath = overrides.descriptions[action.name] || action.name + '.asciidoc';
const examplePath = overrides.examples[action.name] || action.name + '.asciidoc';
const descriptionPath = overrides.descriptions[action.name] || action.name + '.asciidoc';
try {
action.examples = fs.readFileSync(fromRoot('docs/_examples', examplePath), 'utf8');
@ -129,13 +129,13 @@ module.exports = function (branch, done) {
} catch (e) {
action.description = '// no description';
}
})
});
done();
}
function writeApiFile(done) {
var outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js');
const outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js');
fs.writeFileSync(outputPath, templates.apiFile(apiSpec));
console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath);
done();
@ -173,7 +173,7 @@ module.exports = function (branch, done) {
}
function writeMethodDocs(done) {
var filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc');
const filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc');
fs.writeFile(
filename,
templates.apiMethods(docVars),
@ -187,7 +187,7 @@ module.exports = function (branch, done) {
}
function __puke__transformSpec(spec) { // eslint-disable-line
var actions = [];
const actions = [];
// itterate all of the specs within the file, should only be one
_.each(spec, function (def, name) {
@ -198,10 +198,10 @@ module.exports = function (branch, done) {
def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html';
}
var steps = name.split('.');
const steps = name.split('.');
function transformParamKeys(note, param, key) {
var cmlKey = _.camelCase(key);
const cmlKey = _.camelCase(key);
if (cmlKey !== key) {
param.name = key;
}
@ -211,24 +211,24 @@ module.exports = function (branch, done) {
def.url.params = _.transform(def.url.params, transformParamKeys, {});
def.url.parts = _.transform(def.url.parts, transformParamKeys, {});
var allParams = _.extend({}, def.url.params, def.url.parts);
const allParams = _.extend({}, def.url.params, def.url.parts);
_.forOwn(allParams, (paramSpec, paramName) => {
const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName])
const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName]);
if (toMerge) {
_.merge(paramSpec, toMerge, (dest, src) => {
if (_.isArray(dest) && _.isArray(src)) {
return dest.concat(src)
return dest.concat(src);
}
})
});
}
if (paramSpec.options) {
const invalidOpts = paramSpec.options.some(opt => typeof opt !== 'string')
if (invalidOpts) throw new Error(`${name} has options that are not strings...`)
const invalidOpts = paramSpec.options.some(opt => typeof opt !== 'string');
if (invalidOpts) throw new Error(`${name} has options that are not strings...`);
}
})
});
var spec = {
const spec = {
name: name,
methods: _.map(def.methods, function (m) { return m.toUpperCase(); }),
params: def.url.params,
@ -248,15 +248,15 @@ module.exports = function (branch, done) {
spec.requestTimeout = 3000;
}
var urls = _.difference(def.url.paths, overrides.aliases[name]);
var urlSignatures = [];
let urls = _.difference(def.url.paths, overrides.aliases[name]);
const urlSignatures = [];
urls = _.map(urls, function (url) {
var optionalVars = {};
var requiredVars = {};
var param;
var name;
var target;
var match;
const optionalVars = {};
const requiredVars = {};
let param;
let name;
let target;
let match;
if (url.charAt(0) !== '/') {
url = '/' + url;
@ -317,10 +317,10 @@ module.exports = function (branch, done) {
}
// escape method names with "special" keywords
var location = spec.name.split('.').join('.prototype.')
const location = spec.name.split('.').join('.prototype.')
.replace(/(^|\.)(delete|default)(\.|$)/g, '[\'$2\']');
var action = {
const action = {
_methods: spec.methods,
spec: _.pick(spec, [
'params',
@ -339,7 +339,7 @@ module.exports = function (branch, done) {
};
function hasMethod(/* ...methods */) {
for (var i = 0; i < arguments.length; i++) {
for (let i = 0; i < arguments.length; i++) {
if (~action._methods.indexOf(arguments[i])) {
continue;
} else {
@ -352,7 +352,7 @@ module.exports = function (branch, done) {
return hasMethod.apply(null, arguments) && arguments.length === action._methods.length;
}
var method;
let method;
if (action._methods.length === 1) {
method = action._methods[0];

View File

@ -1,8 +1,8 @@
var _ = require('../../../src/lib/utils');
var utils = require('../../../grunt/utils');
var fs = require('fs');
var path = require('path');
const _ = require('../../../src/lib/utils');
const utils = require('../../../grunt/utils');
const fs = require('fs');
const path = require('path');
/**
@ -31,20 +31,20 @@ function stringify(thing, pretty) {
* We'll collect the templates here
* @type {Object}
*/
var templates = {};
const templates = {};
/**
* These keys will be available as local variables to each template
* @type {Object}
*/
var templateGlobals = {
const templateGlobals = {
stringify: stringify,
_: _,
indent: function (block, spaces) {
var indent = _.repeat(' ', spaces);
const indent = _.repeat(' ', spaces);
return block.split('\n').map(function (line) {
return indent + line;
}).join('\n');
@ -58,7 +58,7 @@ var templateGlobals = {
switch (type && type.toLowerCase ? type.toLowerCase() : 'any') {
case 'time':
case 'duration':
if (paramName === 'timestamp') return 'Timestamp'
if (paramName === 'timestamp') return 'Timestamp';
return '<<api-param-type-duration-string,`DurationString`>>';
case 'any':
return 'anything';
@ -96,7 +96,7 @@ var templateGlobals = {
};
fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) {
var name = filename.replace(/\..+$/, '');
const name = filename.replace(/\..+$/, '');
if (name !== 'index') {
templates[name] = _.template(
fs.readFileSync(path.resolve(__dirname, filename), 'utf8'),

View File

@ -2,16 +2,16 @@ module.exports = function (branch, done) {
/**
* Creates a JSON version of the YAML test suite that can be simply bundled for use in the browser.
*/
var jsYaml = require('js-yaml');
var fs = require('fs');
var async = require('async');
var chalk = require('chalk');
var path = require('path');
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
var _ = require(fromRoot('src/lib/utils'));
var tests = {}; // populated in readYamlTests
const jsYaml = require('js-yaml');
const fs = require('fs');
const async = require('async');
const chalk = require('chalk');
const path = require('path');
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
const _ = require(fromRoot('src/lib/utils'));
const tests = {}; // populated in readYamlTests
var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
const esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
// generate the yaml tests
async.series([
@ -21,16 +21,16 @@ module.exports = function (branch, done) {
], done);
function readYamlTests(done) {
var testDir = path.join(esDir, 'rest-api-spec/test/');
const testDir = path.join(esDir, 'rest-api-spec/test/');
function readDirectories(dir) {
fs.readdirSync(dir).forEach(function (filename) {
var filePath = path.join(dir, filename);
var stat = fs.statSync(filePath);
const filePath = path.join(dir, filename);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
readDirectories(filePath);
} else if (filename.match(/\.yaml$/)) {
var file = tests[path.relative(testDir, filePath)] = [];
const file = tests[path.relative(testDir, filePath)] = [];
jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function (doc) {
file.push(doc);
});
@ -43,14 +43,14 @@ module.exports = function (branch, done) {
}
function writeYamlTests(done) {
var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json');
const testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json');
fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8');
console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile);
done();
}
function writeTestIndex(done) {
var file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js');
const file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js');
fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8');
console.log(chalk.white.bold('wrote') + ' YAML index to', file);
done();

View File

@ -1,15 +1,15 @@
var fs = require('fs');
var spawn = require('../_spawn');
var async = require('async');
var _ = require('lodash');
const fs = require('fs');
const spawn = require('../_spawn');
const async = require('async');
const _ = require('lodash');
var root = require('path').join(__dirname, '../..');
var bowerDir = root + '/src/bower_es_js';
const root = require('path').join(__dirname, '../..');
const bowerDir = root + '/src/bower_es_js';
// get both the bower and node package files
var bowerJson = require(bowerDir + '/bower.json');
var bowerPackageJson = require(bowerDir + '/package.json');
var esjsJson = require(root + '/package.json');
const bowerJson = require(bowerDir + '/bower.json');
const bowerPackageJson = require(bowerDir + '/package.json');
const esjsJson = require(root + '/package.json');
// update the version to match the node version
bowerJson.version = esjsJson.version;

View File

@ -4,8 +4,8 @@
*
* It will also instruct the client to use Angular's $http service for it's ajax requests
*/
var AngularConnector = require('./lib/connectors/angular');
var Client = require('./lib/client');
const AngularConnector = require('./lib/connectors/angular');
const Client = require('./lib/client');
process.angular_build = true;
@ -13,7 +13,7 @@ process.angular_build = true;
angular.module('elasticsearch', [])
.factory('esFactory', ['$injector', '$q', function ($injector, $q) {
var factory = function (config) {
const factory = function (config) {
config = config || {};
config.connectionClass = AngularConnector;
config.$injector = $injector;

View File

@ -1,10 +1,10 @@
/* global jQuery */
(function ($) {
process.jquery_build = true;
var es = require('./elasticsearch');
const es = require('./elasticsearch');
function defer() {
var def = $.Deferred();
const def = $.Deferred();
// def.promise is usually a property (in normal implementations)
// we override the promise to keep things working
def.promise = def.promise();

View File

@ -26,9 +26,9 @@
module.exports = Client;
var Transport = require('./transport');
var clientAction = require('./client_action');
var _ = require('./utils');
const Transport = require('./transport');
const clientAction = require('./client_action');
const _ = require('./utils');
function Client(config) {
config = config || {};
@ -71,7 +71,7 @@ function Client(config) {
config.sniffEndpoint = '/_cluster/nodes';
}
var Constructor = EsApiClient;
let Constructor = EsApiClient;
if (config.plugins) {
Constructor.prototype = _.cloneDeep(Constructor.prototype);

View File

@ -1,5 +1,5 @@
var _ = require('./utils');
const _ = require('./utils');
/**
* Constructs a client action factory that uses specific defaults
@ -37,7 +37,7 @@ exports.namespaceFactory = function () {
function makeFactoryWithModifier(modifier) {
modifier = modifier || _.identity;
var factory = function (spec) {
const factory = function (spec) {
spec = modifier(spec);
if (!_.isPlainObject(spec.params)) {
@ -63,7 +63,7 @@ function makeFactoryWithModifier(modifier) {
if (typeof cb === 'function') {
_.nextTick(cb, e);
} else {
var def = this.transport.defer();
const def = this.transport.defer();
def.reject(e);
return def.promise;
}
@ -96,7 +96,7 @@ function makeFactoryWithModifier(modifier) {
return factory;
}
var castType = {
const castType = {
'enum': function validSelection(param, val, name) {
if (_.isString(val) && val.indexOf(',') > -1) {
val = commaSepList(val);
@ -108,7 +108,7 @@ var castType = {
}).join(',');
}
for (var i = 0; i < param.options.length; i++) {
for (let i = 0; i < param.options.length; i++) {
if (param.options[i] === String(val)) {
return param.options[i];
}
@ -183,7 +183,7 @@ var castType = {
};
function resolveUrl(url, params) {
var vars = {}, i, key;
let vars = {}, i, key;
if (url.req) {
// url has required params
@ -192,7 +192,7 @@ function resolveUrl(url, params) {
url.reqParamKeys = _.keys(url.req);
}
for (i = 0; i < url.reqParamKeys.length; i ++) {
for (i = 0; i < url.reqParamKeys.length; i++) {
key = url.reqParamKeys[i];
if (!params.hasOwnProperty(key) || params[key] == null) {
// missing a required param
@ -214,7 +214,7 @@ function resolveUrl(url, params) {
url.optParamKeys = _.keys(url.opt);
}
for (i = 0; i < url.optParamKeys.length; i ++) {
for (i = 0; i < url.optParamKeys.length; i++) {
key = url.optParamKeys[i];
if (params[key]) {
if (castType[url.opt[key].type] || params[key] == null) {
@ -223,7 +223,7 @@ function resolveUrl(url, params) {
vars[key] = params[key];
}
} else {
vars[key] = url.opt[key]['default'];
vars[key] = url.opt[key].default;
}
}
}
@ -243,11 +243,11 @@ function resolveUrl(url, params) {
function exec(transport, spec, params, cb) {
var request = {
const request = {
method: spec.method
};
var query = {};
var i;
const query = {};
let i;
// pass the timeout from the spec
if (spec.requestTimeout) {
@ -297,7 +297,7 @@ function exec(transport, spec, params, cb) {
if (!request.path) {
// there must have been some mimimun requirements that were not met
var minUrl = spec.url || spec.urls[spec.urls.length - 1];
const minUrl = spec.url || spec.urls[spec.urls.length - 1];
throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', '));
}
@ -312,7 +312,7 @@ function exec(transport, spec, params, cb) {
}, []);
}
for (var key in params) {
for (const key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
switch (key) {
case 'body':
@ -339,7 +339,7 @@ function exec(transport, spec, params, cb) {
query[paramSpec.name] = params[key];
}
if (paramSpec['default'] && query[paramSpec.name] === paramSpec['default']) {
if (paramSpec.default && query[paramSpec.name] === paramSpec.default) {
delete query[paramSpec.name];
}
}
@ -350,7 +350,7 @@ function exec(transport, spec, params, cb) {
}
}
for (i = 0; i < spec.requireParamKeys.length; i ++) {
for (i = 0; i < spec.requireParamKeys.length; i++) {
if (!query.hasOwnProperty(spec.requireParamKeys[i])) {
throw new TypeError('Missing required parameter ' + spec.requireParamKeys[i]);
}

View File

@ -1,10 +1,10 @@
module.exports = ConnectionAbstract;
var _ = require('./utils');
var EventEmitter = require('events').EventEmitter;
var Log = require('./log');
var Host = require('./host');
var errors = require('./errors');
const _ = require('./utils');
const EventEmitter = require('events').EventEmitter;
const Log = require('./log');
const Host = require('./host');
const errors = require('./errors');
/**
* Abstract class used for Connection classes
@ -52,10 +52,10 @@ ConnectionAbstract.prototype.ping = function (params, cb) {
cb = typeof cb === 'function' ? cb : null;
}
var requestTimeout = this.pingTimeout;
var requestTimeoutId;
var aborted;
var abort;
let requestTimeout = this.pingTimeout;
let requestTimeoutId;
let aborted;
let abort;
if (params && params.hasOwnProperty('requestTimeout')) {
requestTimeout = params.requestTimeout;
@ -88,7 +88,7 @@ ConnectionAbstract.prototype.ping = function (params, cb) {
};
ConnectionAbstract.prototype.setStatus = function (status) {
var origStatus = this.status;
const origStatus = this.status;
this.status = status;
this.emit('status set', status, origStatus, this);

View File

@ -9,8 +9,8 @@
module.exports = ConnectionPool;
var _ = require('./utils');
var Log = require('./log');
const _ = require('./utils');
const Log = require('./log');
function ConnectionPool(config) {
config = config || {};
@ -107,14 +107,14 @@ ConnectionPool.prototype.select = function (cb) {
* @param {ConnectionAbstract} connection - the connection object itself
*/
ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) {
var index;
let index;
var died = (status === 'dead');
var wasAlreadyDead = (died && oldStatus === 'dead');
var revived = (!died && oldStatus === 'dead');
var noChange = (oldStatus === status);
var from = this._conns[oldStatus];
var to = this._conns[status];
const died = (status === 'dead');
const wasAlreadyDead = (died && oldStatus === 'dead');
const revived = (!died && oldStatus === 'dead');
const noChange = (oldStatus === status);
const from = this._conns[oldStatus];
const to = this._conns[status];
if (noChange && !died) {
return true;
@ -150,8 +150,8 @@ ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, co
* @param {ConnectionAbstract} connection
*/
ConnectionPool.prototype._onConnectionRevived = function (connection) {
var timeout;
for (var i = 0; i < this._timeouts.length; i++) {
let timeout;
for (let i = 0; i < this._timeouts.length; i++) {
if (this._timeouts[i].conn === connection) {
timeout = this._timeouts[i];
if (timeout.id) {
@ -169,9 +169,9 @@ ConnectionPool.prototype._onConnectionRevived = function (connection) {
* @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true
*/
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
var timeout;
let timeout;
if (alreadyWasDead) {
for (var i = 0; i < this._timeouts.length; i++) {
for (let i = 0; i < this._timeouts.length; i++) {
if (this._timeouts[i].conn === connection) {
timeout = this._timeouts[i];
break;
@ -198,17 +198,17 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea
clearTimeout(timeout.id);
}
var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout);
const ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout);
timeout.id = setTimeout(timeout.revive, ms);
timeout.runAt = _.now() + ms;
};
ConnectionPool.prototype._selectDeadConnection = function (cb) {
var orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
var log = this.log;
const orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
const log = this.log;
process.nextTick(function next() {
var timeout = orderedTimeouts.shift();
const timeout = orderedTimeouts.shift();
if (!timeout) {
cb(void 0);
return;
@ -247,7 +247,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
* @param {Number} [limit] - optional limit on the number of connections to return
*/
ConnectionPool.prototype.getConnections = function (status, limit) {
var list;
let list;
if (status) {
list = this._conns[status];
} else {
@ -304,11 +304,11 @@ ConnectionPool.prototype.removeConnection = function (connection) {
* @param {Host[]} hosts - An array of Host instances.
*/
ConnectionPool.prototype.setHosts = function (hosts) {
var connection;
var i;
var id;
var host;
var toRemove = _.clone(this.index);
let connection;
let i;
let id;
let host;
const toRemove = _.clone(this.index);
for (i = 0; i < hosts.length; i++) {
host = hosts[i];
@ -322,7 +322,7 @@ ConnectionPool.prototype.setHosts = function (hosts) {
}
}
var removeIds = _.keys(toRemove);
const removeIds = _.keys(toRemove);
for (i = 0; i < removeIds.length; i++) {
this.removeConnection(this.index[removeIds[i]]);
}

View File

@ -6,14 +6,14 @@
*/
module.exports = AngularConnector;
var _ = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;
const _ = require('../utils');
const ConnectionAbstract = require('../connection');
const ConnectionFault = require('../errors').ConnectionFault;
function AngularConnector(host, config) {
ConnectionAbstract.call(this, host, config);
var self = this;
const self = this;
config.$injector.invoke(['$http', '$q', function ($http, $q) {
self.$q = $q;
self.$http = $http;
@ -23,7 +23,7 @@ function AngularConnector(host, config) {
_.inherits(AngularConnector, ConnectionAbstract);
AngularConnector.prototype.request = function (params, cb) {
var abort = this.$q.defer();
const abort = this.$q.defer();
this.$http({
method: params.method,

View File

@ -1,9 +1,9 @@
var opts = {
const opts = {
xhr: require('./xhr'),
jquery: require('./jquery'),
angular: require('./angular')
};
var _ = require('../utils');
const _ = require('../utils');
// remove modules that have been ignored by browserify
_.each(opts, function (conn, name) {

View File

@ -8,16 +8,16 @@
*/
module.exports = HttpConnector;
var handles = {
const handles = {
http: require('http'),
https: require('https')
};
var _ = require('../utils');
var parseUrl = require('url').parse;
var qs = require('querystring');
var AgentKeepAlive = require('agentkeepalive');
var ConnectionAbstract = require('../connection');
var zlib = require('zlib');
const _ = require('../utils');
const parseUrl = require('url').parse;
const qs = require('querystring');
const AgentKeepAlive = require('agentkeepalive');
const ConnectionAbstract = require('../connection');
const zlib = require('zlib');
/**
* Connector used to talk to an elasticsearch node via HTTP
@ -51,9 +51,9 @@ _.inherits(HttpConnector, ConnectionAbstract);
HttpConnector.prototype.onStatusSet = _.handler(function (status) {
if (status === 'closed') {
var agent = this.agent;
var toRemove = [];
var collectSockets = function (sockets, host) {
const agent = this.agent;
const toRemove = [];
const collectSockets = function (sockets, host) {
_.each(sockets, function (s) {
if (s) toRemove.push([host, s]);
});
@ -65,7 +65,7 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) {
_.each(agent.sockets, collectSockets);
_.each(agent.freeSockets, collectSockets);
_.each(toRemove, function (args) {
var host = args[0], socket = args[1];
let host = args[0], socket = args[1];
agent.removeSocket(socket, parseUrl(host));
socket.destroy();
});
@ -73,7 +73,7 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) {
});
HttpConnector.prototype.createAgent = function (config) {
var Agent = this.hand.Agent; // the class
let Agent = this.hand.Agent; // the class
if (config.forever) {
config.keepAlive = config.forever;
@ -88,7 +88,7 @@ HttpConnector.prototype.createAgent = function (config) {
};
HttpConnector.prototype.makeAgentConfig = function (config) {
var agentConfig = {
const agentConfig = {
keepAlive: config.keepAlive,
keepAliveMsecs: config.keepAliveInterval,
maxSockets: config.maxSockets,
@ -105,9 +105,9 @@ HttpConnector.prototype.makeAgentConfig = function (config) {
HttpConnector.prototype.makeReqParams = function (params) {
params = params || {};
var host = this.host;
const host = this.host;
var reqParams = {
const reqParams = {
method: params.method || 'GET',
protocol: host.protocol + ':',
hostname: host.host,
@ -121,7 +121,7 @@ HttpConnector.prototype.makeReqParams = function (params) {
reqParams.path = '/';
}
var query = host.getQuery(params.query);
const query = host.getQuery(params.query);
if (query) {
reqParams.path = reqParams.path + '?' + qs.stringify(query);
}
@ -130,19 +130,19 @@ HttpConnector.prototype.makeReqParams = function (params) {
};
HttpConnector.prototype.request = function (params, cb) {
var incoming;
var timeoutId;
var request;
var status = 0;
var headers = {};
var log = this.log;
var response;
let incoming;
let timeoutId;
let request;
let status = 0;
let headers = {};
const log = this.log;
let response;
var reqParams = this.makeReqParams(params);
const reqParams = this.makeReqParams(params);
// general clean-up procedure to run after the request
// completes, has an error, or is aborted.
var cleanUp = _.bind(function (err) {
const cleanUp = _.bind(function (err) {
clearTimeout(timeoutId);
request && request.removeAllListeners();
@ -166,7 +166,7 @@ HttpConnector.prototype.request = function (params, cb) {
headers = incoming.headers;
response = '';
var encoding = (headers['content-encoding'] || '').toLowerCase();
const encoding = (headers['content-encoding'] || '').toLowerCase();
if (encoding === 'gzip' || encoding === 'deflate') {
incoming = incoming.pipe(zlib.createUnzip());
}

View File

@ -7,9 +7,9 @@
*/
module.exports = JqueryConnector;
var _ = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;
const _ = require('../utils');
const ConnectionAbstract = require('../connection');
const ConnectionFault = require('../errors').ConnectionFault;
function JqueryConnector(host, config) {
ConnectionAbstract.call(this, host, config);
@ -17,7 +17,7 @@ function JqueryConnector(host, config) {
_.inherits(JqueryConnector, ConnectionAbstract);
JqueryConnector.prototype.request = function (params, cb) {
var ajax = {
const ajax = {
url: this.host.makeUrl(params),
data: params.body,
type: params.method,

View File

@ -7,10 +7,10 @@ module.exports = XhrConnector;
/* jshint browser:true */
var _ = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;
var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent));
const _ = require('../utils');
const ConnectionAbstract = require('../connection');
const ConnectionFault = require('../errors').ConnectionFault;
const asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent));
function XhrConnector(host, config) {
ConnectionAbstract.call(this, host, config);
@ -21,7 +21,7 @@ _.inherits(XhrConnector, ConnectionAbstract);
* Simply returns an XHR object cross browser
* @type {Function}
*/
var getXhr = _.noop;
let getXhr = _.noop;
if (typeof XMLHttpRequest !== 'undefined') {
// rewrite the getXhr method to always return the native implementation
@ -34,7 +34,7 @@ if (typeof XMLHttpRequest !== 'undefined') {
.map(function (appName) {
/* jshint unused: false */
try {
var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
const test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
return function () {
return new window.ActiveXObject(appName);
};
@ -51,19 +51,19 @@ if (!getXhr) {
}
XhrConnector.prototype.request = function (params, cb) {
var xhr = getXhr();
var timeoutId;
var host = this.host;
var log = this.log;
const xhr = getXhr();
let timeoutId;
const host = this.host;
const log = this.log;
var url = host.makeUrl(params);
var headers = host.getHeaders(params.headers);
var async = params.async === false ? false : asyncDefault;
const url = host.makeUrl(params);
const headers = host.getHeaders(params.headers);
const async = params.async === false ? false : asyncDefault;
xhr.open(params.method || 'GET', url, async);
if (headers) {
for (var key in headers) {
for (const key in headers) {
if (headers[key] !== void 0) {
xhr.setRequestHeader(key, headers[key]);
}
@ -74,7 +74,7 @@ XhrConnector.prototype.request = function (params, cb) {
if (xhr.readyState === 4) {
clearTimeout(timeoutId);
log.trace(params.method, url, params.body, xhr.responseText, xhr.status);
var err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
const err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
cb(err, xhr.responseText, xhr.status);
}
};

View File

@ -1,8 +1,8 @@
var _ = require('./utils');
var errors = module.exports;
const _ = require('./utils');
const errors = module.exports;
var canCapture = (typeof Error.captureStackTrace === 'function');
var canStack = !!(new Error()).stack;
const canCapture = (typeof Error.captureStackTrace === 'function');
const canStack = !!(new Error()).stack;
function ErrorAbstract(msg, constructor, metadata) {
this.message = msg;
@ -91,7 +91,7 @@ errors.RequestTypeError = function RequestTypeError(feature) {
};
_.inherits(errors.RequestTypeError, ErrorAbstract);
var statusCodes = [
const statusCodes = [
[300, 'Multiple Choices'],
[301, 'Moved Permanently'],
[302, 'Found'],
@ -137,18 +137,18 @@ var statusCodes = [
];
_.each(statusCodes, function createStatusCodeError(tuple) {
var status = tuple[0];
var names = tuple[1];
var allNames = [].concat(names, status);
var primaryName = allNames[0];
var className = _.studlyCase(primaryName);
const status = tuple[0];
const names = tuple[1];
let allNames = [].concat(names, status);
const primaryName = allNames[0];
const className = _.studlyCase(primaryName);
allNames = _.uniq(allNames.concat(className));
function StatusCodeError(msg, metadata) {
this.status = status;
this.displayName = className;
var esErrObject = null;
let esErrObject = null;
if (_.isPlainObject(msg)) {
esErrObject = msg;
msg = null;
@ -167,7 +167,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
memo += '[' + cause.type + '] ' + cause.reason;
var extraData = _.omit(cause, ['type', 'reason']);
const extraData = _.omit(cause, ['type', 'reason']);
if (_.size(extraData)) {
memo += ', with ' + prettyPrint(extraData);
}
@ -192,20 +192,20 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
function prettyPrint(data) {
const path = []
const path = [];
return (function print(v) {
if (typeof v === 'object') {
if (path.indexOf(v) > -1) return '[circular]'
path.push(v)
if (path.indexOf(v) > -1) return '[circular]';
path.push(v);
try {
return '{ ' + _.map(v, function (subv, name) {
return name + '=' + print(subv)
}).join(' & ') + ' }'
return name + '=' + print(subv);
}).join(' & ') + ' }';
} finally {
path.pop()
path.pop();
}
} else {
return JSON.stringify(v)
return JSON.stringify(v);
}
}(data))
}(data));
}

View File

@ -4,13 +4,13 @@
*/
module.exports = Host;
var url = require('url');
var qs = require('querystring');
var _ = require('./utils');
const url = require('url');
const qs = require('querystring');
const _ = require('./utils');
var startsWithProtocolRE = /^([a-z]+:)?\/\//;
var defaultProto = 'http:';
var btoa;
const startsWithProtocolRE = /^([a-z]+:)?\/\//;
let defaultProto = 'http:';
let btoa;
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
defaultProto = window.location.protocol;
@ -21,13 +21,13 @@ btoa = btoa || function (data) {
return (new Buffer(data, 'utf8')).toString('base64');
};
var urlParseFields = [
const urlParseFields = [
'protocol', 'hostname', 'pathname', 'port', 'auth', 'query'
];
var simplify = ['host', 'path'];
const simplify = ['host', 'path'];
var sslDefaults = {
const sslDefaults = {
pfx: null,
key: null,
passphrase: null,
@ -61,11 +61,11 @@ function Host(config, globalConfig) {
this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults);
if (typeof config === 'string') {
var firstColon = config.indexOf(':');
var firstSlash = config.indexOf('/');
var noSlash = firstSlash === -1;
var portNoPath = firstColon > -1 && noSlash;
var portWithPath = !portNoPath && firstColon < firstSlash;
const firstColon = config.indexOf(':');
const firstSlash = config.indexOf('/');
const noSlash = firstSlash === -1;
const portNoPath = firstColon > -1 && noSlash;
const portWithPath = !portNoPath && firstColon < firstSlash;
if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) {
config = defaultProto + '//' + config;
}
@ -73,7 +73,7 @@ function Host(config, globalConfig) {
// default logic for the port is to use 9200 for the default. When a string is specified though,
// we will use the default from the protocol of the string.
if (!config.port) {
var proto = config.protocol || 'http';
let proto = config.protocol || 'http';
if (proto.charAt(proto.length - 1) === ':') {
proto = proto.substring(0, proto.length - 1);
}
@ -86,7 +86,7 @@ function Host(config, globalConfig) {
if (_.isObject(config)) {
// move hostname/portname to host/port semi-intelligently.
_.each(simplify, function (to) {
var from = to + 'name';
const from = to + 'name';
if (config[from] && config[to]) {
if (config[to].indexOf(config[from]) === 0) {
config[to] = config[from];
@ -101,7 +101,7 @@ function Host(config, globalConfig) {
}
if (!config.auth && globalConfig.httpAuth) {
config.auth = globalConfig.httpAuth
config.auth = globalConfig.httpAuth;
}
if (config.auth) {
@ -145,14 +145,14 @@ function Host(config, globalConfig) {
Host.prototype.makeUrl = function (params) {
params = params || {};
// build the port
var port = '';
let port = '';
if (this.port !== Host.defaultPorts[this.protocol]) {
// add an actual port
port = ':' + this.port;
}
// build the path
var path = '' + (this.path || '') + (params.path || '');
let path = '' + (this.path || '') + (params.path || '');
// if path doesn't start with '/' add it.
if (path.charAt(0) !== '/') {
@ -160,7 +160,7 @@ Host.prototype.makeUrl = function (params) {
}
// build the query string
var query = qs.stringify(this.getQuery(params.query));
const query = qs.stringify(this.getQuery(params.query));
if (this.host) {
return this.protocol + '://' + this.host + port + path + (query ? '?' + query : '');
@ -175,7 +175,7 @@ function objectPropertyGetter(prop, preOverride) {
overrides = preOverride.call(this, overrides);
}
var obj = this[prop];
let obj = this[prop];
if (!obj && !overrides) {
return null;
}

View File

@ -1,6 +1,6 @@
var _ = require('./utils');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
const _ = require('./utils');
const url = require('url');
const EventEmitter = require('events').EventEmitter;
/**
* Log bridge, which is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
@ -21,8 +21,8 @@ function Log(config) {
config = config || {};
if (!config.log) return;
var i;
var outputs;
let i;
let outputs;
if (_.isArrayOfStrings(config.log)) {
outputs = [{
@ -158,7 +158,7 @@ Log.parseLevels = function (input) {
/* fall through */
case 'object':
if (_.isArray(input)) {
var valid = _.intersection(input, Log.levels);
const valid = _.intersection(input, Log.levels);
if (valid.length === input.length) {
return valid;
}
@ -209,7 +209,7 @@ Log.prototype.addOutput = function (config) {
config.levels = Log.parseLevels(config.levels || config.level || 'warning');
delete config.level;
var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio');
const Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio');
return new Logger(this, config);
};

View File

@ -1,4 +1,4 @@
var _ = require('./utils');
const _ = require('./utils');
/**
* Abstract class providing common functionality to loggers
@ -27,7 +27,7 @@ function padNumToTen(n) {
* @return {String} - Timestamp in ISO 8601 UTC
*/
LoggerAbstract.prototype.timestamp = function () {
var d = new Date();
const d = new Date();
return d.getUTCFullYear() + '-' +
padNumToTen(d.getUTCMonth() + 1) + '-' +
padNumToTen(d.getUTCDate()) + 'T' +
@ -37,7 +37,7 @@ LoggerAbstract.prototype.timestamp = function () {
};
function indent(text, spaces) {
var space = _.repeat(' ', spaces || 2);
const space = _.repeat(' ', spaces || 2);
return (text || '').split(/\r?\n/).map(function (line) {
return space + line;
}).join('\n');
@ -65,7 +65,7 @@ LoggerAbstract.prototype.setupListeners = function (levels) {
this.listeningLevels = [];
_.each(levels, _.bind(function (level) {
var fnName = 'on' + _.ucfirst(level);
const fnName = 'on' + _.ucfirst(level);
if (this.bound[fnName]) {
this.listeningLevels.push(level);
this.log.on(level, this.bound[fnName]);

View File

@ -12,8 +12,8 @@
module.exports = Console;
var LoggerAbstract = require('../logger');
var _ = require('../utils');
const LoggerAbstract = require('../logger');
const _ = require('../utils');
function Console(log, config) {
LoggerAbstract.call(this, log, config);
@ -48,7 +48,7 @@ Console.prototype.write = function (label, message, to) {
* @return {undefined}
*/
Console.prototype.onError = _.handler(function (e) {
var to = console.error ? 'error' : 'log';
const to = console.error ? 'error' : 'log';
this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to);
});

View File

@ -11,9 +11,9 @@
module.exports = File;
var StreamLogger = require('./stream');
var _ = require('../utils');
var fs = require('fs');
const StreamLogger = require('./stream');
const _ = require('../utils');
const fs = require('fs');
function File(log, config) {
config = config || {};
@ -32,7 +32,7 @@ function File(log, config) {
_.inherits(File, StreamLogger);
File.prototype.onProcessExit = _.handler(function () {
var toWrite = _.getUnwrittenFromStream(this.stream);
const toWrite = _.getUnwrittenFromStream(this.stream);
if (toWrite) {
fs.appendFileSync(this.path, toWrite);
}

View File

@ -12,14 +12,14 @@
module.exports = Stdio;
var chalk = require('chalk');
const chalk = require('chalk');
// let the user define if they want color in the client config.
chalk.enabled = true;
var LoggerAbstract = require('../logger');
var _ = require('../utils');
const LoggerAbstract = require('../logger');
const _ = require('../utils');
var defaultColors = {
const defaultColors = {
error: chalk.red.bold,
warning: chalk.yellow.bold,
info: chalk.cyan.bold,

View File

@ -12,8 +12,8 @@
module.exports = Stream;
var LoggerAbstract = require('../logger');
var _ = require('../utils');
const LoggerAbstract = require('../logger');
const _ = require('../utils');
function Stream(log, config) {
LoggerAbstract.call(this, log, config);
@ -36,7 +36,7 @@ Stream.prototype.cleanUpListeners = _.handler(function () {
// flush the write buffer to stderr synchronously
Stream.prototype.onProcessExit = _.handler(function () {
// process is dying, lets manually flush the buffer synchronously to stderr.
var unwritten = _.getUnwrittenFromStream(this.stream);
const unwritten = _.getUnwrittenFromStream(this.stream);
if (unwritten) {
console.error('Log stream did not get to finish writing. Flushing to stderr');
console.error(unwritten);

View File

@ -12,10 +12,10 @@
module.exports = Tracer;
var StreamLogger = require('./stream');
var fs = require('fs');
var _ = require('../utils');
var url = require('url');
const StreamLogger = require('./stream');
const fs = require('fs');
const _ = require('../utils');
const url = require('url');
function Tracer(log, config) {
if (config.path === false) {
@ -31,22 +31,22 @@ function Tracer(log, config) {
}
_.inherits(Tracer, StreamLogger);
var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query'];
const usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query'];
Tracer.prototype._formatTraceMessage = function (req) {
var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields);
const reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields);
var originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port'));
const originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port'));
reqUrl.port = this.curlPort;
reqUrl.hostname = this.curlHost;
reqUrl.query = _.defaults(reqUrl.query || {}, { pretty: true });
/* jshint quotmark: double */
var curlCall =
const curlCall =
'# ' + originalHost + '\n' +
"curl '" + url.format(reqUrl).replace(/'/g, "\\'") + "' -X" + req.method.toUpperCase() +
(req.body ? " -d '" + this._prettyJson(req.body) + "'" : '');
'curl \'' + url.format(reqUrl).replace(/'/g, '\\\'') + '\' -X' + req.method.toUpperCase() +
(req.body ? ' -d \'' + this._prettyJson(req.body) + '\'' : '');
/* jshint quotmark: single */
return {
@ -62,7 +62,7 @@ function comment(str) {
}
Tracer.prototype.write = function (label, msg) {
var lead = comment(label + ': ' + this.timestamp()) + '\n';
const lead = comment(label + ': ' + this.timestamp()) + '\n';
if (typeof msg === 'string') {
this.stream.write(lead + comment(msg) + '\n\n', 'utf8');
} else {

View File

@ -1,14 +1,14 @@
var _ = require('./utils');
const _ = require('./utils');
var extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/;
const extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/;
function makeNodeParser(hostProp) {
return function (nodes) {
return _.transform(nodes, function (hosts, node, id) {
var address = _.get(node, hostProp)
let address = _.get(node, hostProp);
if (!address) return;
var host = {
const host = {
host: undefined,
port: undefined,
_meta: {
@ -18,13 +18,13 @@ function makeNodeParser(hostProp) {
}
};
var malformedError = new Error(
const malformedError = new Error(
'Malformed ' + hostProp + '.' +
' Got ' + JSON.stringify(address) +
' and expected it to match "{hostname?}/{ip}:{port}".'
);
var matches1x = extractHostPartsRE1x.exec(address);
const matches1x = extractHostPartsRE1x.exec(address);
if (matches1x) {
host.host = matches1x[1] || matches1x[2];
host.port = parseInt(matches1x[3], 10);
@ -33,7 +33,7 @@ function makeNodeParser(hostProp) {
}
if (address.indexOf('/') > -1) {
var withHostParts = address.split('/');
const withHostParts = address.split('/');
if (withHostParts.length !== 2) throw malformedError;
host.host = withHostParts.shift();
@ -44,7 +44,7 @@ function makeNodeParser(hostProp) {
throw malformedError;
}
var addressParts = address.split(':');
const addressParts = address.split(':');
if (addressParts.length !== 2) {
throw malformedError;
}

View File

@ -7,7 +7,7 @@
* @return {Connection} - The selected connection
*/
module.exports = function (connections) {
var connection = connections[0];
const connection = connections[0];
connections.push(connections.shift());
return connection;
};

View File

@ -1,6 +1,6 @@
/* global angular */
var _ = require('../utils');
var JsonSerializer = require('../serializers/json');
const _ = require('../utils');
const JsonSerializer = require('../serializers/json');
function AngularSerializer() {}
_.inherits(AngularSerializer, JsonSerializer);

View File

@ -4,7 +4,7 @@
*/
module.exports = Json;
var _ = require('../utils');
const _ = require('../utils');
function Json() {}
@ -44,7 +44,7 @@ Json.prototype.deserialize = function (str) {
};
Json.prototype.bulkBody = function (val) {
var body = '', i;
let body = '', i;
if (_.isArray(val)) {
for (i = 0; i < val.length; i++) {

View File

@ -4,25 +4,25 @@
*/
module.exports = Transport;
var _ = require('./utils');
var errors = require('./errors');
var Host = require('./host');
var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');
var findCommonProtocol = require('./transport/find_common_protocol');
const _ = require('./utils');
const errors = require('./errors');
const Host = require('./host');
const patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');
const findCommonProtocol = require('./transport/find_common_protocol');
function Transport(config) {
var self = this;
const self = this;
config = self._config = config || {};
var LogClass = (typeof config.log === 'function') ? config.log : require('./log');
const LogClass = (typeof config.log === 'function') ? config.log : require('./log');
config.log = self.log = new LogClass(config);
// setup the connection pool
var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main');
const ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main');
self.connectionPool = new ConnectionPool(config);
// setup the serializer
var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json');
const Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json');
self.serializer = new Serializer(config);
// setup the nodesToHostCallback
@ -42,14 +42,14 @@ function Transport(config) {
}
// randomizeHosts option
var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;
const randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;
if (config.host) {
config.hosts = config.host;
}
if (config.hosts) {
var hostsConfig = _.createArray(config.hosts, function (val) {
let hostsConfig = _.createArray(config.hosts, function (val) {
if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {
return val;
}
@ -104,10 +104,10 @@ Transport.prototype.defer = function () {
throw new Error(
'No Promise implementation found. In order for elasticsearch-js to create promises ' +
'either specify the `defer` configuration or include a global Promise shim'
)
);
}
var defer = {};
const defer = {};
defer.promise = new Promise(function (resolve, reject) {
defer.resolve = resolve;
defer.reject = reject;
@ -133,19 +133,19 @@ Transport.prototype.defer = function () {
* @param {Function} cb - A function to call back with (error, responseBody, responseStatus)
*/
Transport.prototype.request = function (params, cb) {
var self = this;
var remainingRetries = this.maxRetries;
var requestTimeout = this.requestTimeout;
const self = this;
let remainingRetries = this.maxRetries;
let requestTimeout = this.requestTimeout;
var connection; // set in sendReqWithConnection
var aborted = false; // several connector will respond with an error when the request is aborted
var requestAborter; // an abort function, returned by connection#request()
var requestTimeoutId; // the id of the ^timeout
var ret; // the object returned to the user, might be a promise
var defer; // the defer object, will be set when we are using promises.
let connection; // set in sendReqWithConnection
let aborted = false; // several connector will respond with an error when the request is aborted
let requestAborter; // an abort function, returned by connection#request()
let requestTimeoutId; // the id of the ^timeout
let ret; // the object returned to the user, might be a promise
let defer; // the defer object, will be set when we are using promises.
var body = params.body;
var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) {
let body = params.body;
const headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) {
headers[String(name).toLowerCase()] = val;
});
@ -173,8 +173,8 @@ Transport.prototype.request = function (params, cb) {
// serialize the body
if (body) {
var serializer = self.serializer;
var serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize'];
const serializer = self.serializer;
const serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize'];
body = serializeFn.call(serializer, body);
if (!headers['content-type']) {
@ -230,7 +230,7 @@ Transport.prototype.request = function (params, cb) {
if (err) {
connection.setStatus('dead');
var errMsg = err.message || '';
let errMsg = err.message || '';
errMsg =
'\n' +
@ -261,8 +261,8 @@ Transport.prototype.request = function (params, cb) {
}
self._timeout(requestTimeoutId);
var parsedBody;
var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));
let parsedBody;
const isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));
if (!err && body) {
if (isJson) {
@ -283,7 +283,7 @@ Transport.prototype.request = function (params, cb) {
&& (!params.ignore || !_.include(params.ignore, status))
) {
var errorMetadata = _.pick(params.req, ['path', 'query', 'body']);
const errorMetadata = _.pick(params.req, ['path', 'query', 'body']);
errorMetadata.statusCode = status;
errorMetadata.response = body;
@ -356,8 +356,8 @@ Transport.prototype.request = function (params, cb) {
Transport.prototype._timeout = function (cb, delay) {
if (this.closed) return;
var id;
var timers = this._timers || (this._timers = []);
let id;
const timers = this._timers || (this._timers = []);
if ('function' !== typeof cb) {
id = cb;
@ -378,7 +378,7 @@ Transport.prototype._timeout = function (cb, delay) {
if (id) {
clearTimeout(id);
var i = this._timers.indexOf(id);
const i = this._timers.indexOf(id);
if (i !== -1) {
this._timers.splice(i, 1);
}
@ -392,10 +392,10 @@ Transport.prototype._timeout = function (cb, delay) {
* @param {Function} cb - Function to call back once complete
*/
Transport.prototype.sniff = function (cb) {
var self = this;
var nodesToHostCallback = this.nodesToHostCallback;
var log = this.log;
var sniffedNodesProtocol = this.sniffedNodesProtocol;
const self = this;
const nodesToHostCallback = this.nodesToHostCallback;
const log = this.log;
const sniffedNodesProtocol = this.sniffedNodesProtocol;
// make cb a function if it isn't
cb = typeof cb === 'function' ? cb : _.noop;
@ -414,7 +414,7 @@ Transport.prototype.sniff = function (cb) {
method: 'GET'
}, function (err, resp, status) {
if (!err && resp && resp.nodes) {
var hostsConfigs;
let hostsConfigs;
try {
hostsConfigs = nodesToHostCallback(resp.nodes);
@ -441,7 +441,7 @@ Transport.prototype.sniff = function (cb) {
* that will be used to create Host objects.
*/
Transport.prototype.setHosts = function (hostsConfigs) {
var globalConfig = this._config;
const globalConfig = this._config;
this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) {
return (conf instanceof Host) ? conf : new Host(conf, globalConfig);
}));

View File

@ -1,14 +1,14 @@
var isEmpty = require('lodash.isempty');
const isEmpty = require('lodash.isempty');
module.exports = function (hosts) {
if (isEmpty(hosts)) return false;
var commonProtocol = hosts.shift().protocol;
for (var i = 0; i < hosts.length; i++) {
const commonProtocol = hosts.shift().protocol;
for (let i = 0; i < hosts.length; i++) {
if (commonProtocol !== hosts[i].protocol) {
return false;
}
}
return commonProtocol;
}
};

View File

@ -1,4 +1,4 @@
var _ = require('../utils');
const _ = require('../utils');
/**
@ -11,9 +11,9 @@ var _ = require('../utils');
* @return {undefined}
*/
module.exports = function setupSniffOnConnectionFault(transport) {
var failures = 0;
var pool = transport.connectionPool;
var originalOnDied = pool._onConnectionDied;
let failures = 0;
const pool = transport.connectionPool;
const originalOnDied = pool._onConnectionDied;
// do the actual sniff, if the sniff is unable to
// connect to a node this function will be called again by the connectionPool
@ -24,8 +24,8 @@ module.exports = function setupSniffOnConnectionFault(transport) {
// create a function that will count down to a
// point n milliseconds into the future
var countdownTo = function (ms) {
var start = _.now();
const countdownTo = function (ms) {
const start = _.now();
return function () {
return start - ms;
};
@ -33,12 +33,12 @@ module.exports = function setupSniffOnConnectionFault(transport) {
// overwrite the function, but still call it
pool._onConnectionDied = function (connection, wasAlreadyDead) {
var ret = originalOnDied.call(pool, connection, wasAlreadyDead);
const ret = originalOnDied.call(pool, connection, wasAlreadyDead);
// clear the failures if this is the first failure we have seen
failures = work.timerId ? failures + 1 : 0;
var ms = pool.calcDeadTimeout(failures, 1000);
const ms = pool.calcDeadTimeout(failures, 1000);
if (work.timerId && ms < work.timerId && work.countdown()) {
// clear the timer

View File

@ -1,6 +1,6 @@
var path = require('path');
var nodeUtils = require('util');
var lodash = require('lodash');
const path = require('path');
const nodeUtils = require('util');
const lodash = require('lodash');
/**
* Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) +
@ -10,7 +10,7 @@ var lodash = require('lodash');
* @class utils
* @static
*/
var _ = lodash.assign({}, lodash, nodeUtils);
const _ = lodash.assign({}, lodash, nodeUtils);
/**
* Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2)
@ -67,7 +67,7 @@ _.each([
'Function',
'RegExp'
], function (type) {
var check = _['is' + type];
const check = _['is' + type];
_['isArrayOf' + type + 's'] = function (arr) {
// quick shallow check of arrays
@ -94,10 +94,10 @@ _.ucfirst = function (word) {
*/
function adjustWordCase(firstWordCap, otherWordsCap, sep) {
return function (string) {
var i = 0;
var words = [];
var word = '';
var code, c, upper, lower;
let i = 0;
const words = [];
let word = '';
let code, c, upper, lower;
for (; i < string.length; i++) {
code = string.charCodeAt(i);
@ -210,7 +210,7 @@ _.isNumeric = function (val) {
};
// regexp to test for intervals
var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/;
const intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/;
/**
* Test if a string represents an interval (eg. 1m, 2Y)
@ -315,7 +315,7 @@ _.scheduled = _.handler;
*/
_.makeBoundMethods = function (obj) {
obj.bound = {};
for (var prop in obj) {
for (const prop in obj) {
// dearest maintainer, we want to look through the prototype
if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) {
obj.bound[prop] = _.bind(obj[prop], obj);
@ -332,7 +332,7 @@ _.noop = function () {};
* @return {Function|undefined} - If a valid option was specified, then the constructor is returned
*/
_.funcEnum = function (config, name, opts, def) {
var val = config[name];
const val = config[name];
switch (typeof val) {
case 'undefined':
return opts[def];
@ -371,9 +371,9 @@ _.funcEnum = function (config, name, opts, def) {
*/
_.createArray = function (input, transform) {
transform = typeof transform === 'function' ? transform : _.identity;
var output = [];
var item;
var i;
const output = [];
let item;
let i;
if (!_.isArray(input)) {
input = [input];
@ -399,11 +399,11 @@ _.createArray = function (input, transform) {
* @return {string} - the remaining test to be written to the stream
*/
_.getUnwrittenFromStream = function (stream) {
var writeBuffer = _.getStreamWriteBuffer(stream);
const writeBuffer = _.getStreamWriteBuffer(stream);
if (!writeBuffer) return;
// flush the write buffer
var out = '';
let out = '';
if (!writeBuffer.length) return out;
_.each(writeBuffer, function (writeReq) {
@ -423,7 +423,7 @@ _.getUnwrittenFromStream = function (stream) {
_.getStreamWriteBuffer = function (stream) {
if (!stream || !stream._writableState) return;
var writeState = stream._writableState;
const writeState = stream._writableState;
if (writeState.getBuffer) {
return writeState.getBuffer();
@ -433,7 +433,7 @@ _.getStreamWriteBuffer = function (stream) {
};
_.clearWriteStreamBuffer = function (stream) {
var buffer = _.getStreamWriteBuffer(stream);
const buffer = _.getStreamWriteBuffer(stream);
return buffer && buffer.splice(0);
};

View File

@ -1,10 +1,10 @@
var clock = require('sinon').useFakeTimers();
var Client = require('../../src/elasticsearch').Client;
var _ = require('lodash');
var times = require('async').times;
const clock = require('sinon').useFakeTimers();
const Client = require('../../src/elasticsearch').Client;
const _ = require('lodash');
const times = require('async').times;
process.once('message', function (port) {
var es = new Client({
const es = new Client({
host: 'http://127.0.0.1:' + port,
log: false
});
@ -19,8 +19,8 @@ process.once('message', function (port) {
}, done);
clock.tick(10);
}, function (err) {
var conns = es.transport.connectionPool._conns;
var sockets = _([].concat(conns.dead, conns.alive))
const conns = es.transport.connectionPool._conns;
const sockets = _([].concat(conns.dead, conns.alive))
.transform(function (sockets, conn) {
sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets));
}, [])
@ -29,7 +29,7 @@ process.once('message', function (port) {
es.close();
var out = {
const out = {
socketCount: err || sockets.length,
remaining: _.filter(sockets, { destroyed: true }).length - sockets.length,
timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String)

View File

@ -4,13 +4,13 @@
// which prevent sinon from being able to ensure
// timeouts aren't being left behind
var express = require('express');
var app = express().post('/_search', function (req, res) {
const express = require('express');
const app = express().post('/_search', function (req, res) {
res.json(200, { hits: { hits: [] } });
});
var server = require('http').createServer(app);
const server = require('http').createServer(app);
server.listen(function () {
var port = server.address().port;
const port = server.address().port;
process.connected ? process.send(port) : console.log(port);
});

View File

@ -1,22 +1,22 @@
var BROWSER = process.env.browser;
var VERBOSE = process.env.VERBOSE;
var JENKINS = !!process.env.JENKINS_HOME;
const BROWSER = process.env.browser;
const VERBOSE = process.env.VERBOSE;
const JENKINS = !!process.env.JENKINS_HOME;
var es;
let es;
if (BROWSER) {
es = window.elasticsearch;
} else {
es = require('../../../src/elasticsearch');
}
var _ = require('../../../src/lib/utils');
var path = require('path');
var fs = require('fs');
var fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname));
var Bluebird = require('bluebird');
const _ = require('../../../src/lib/utils');
const path = require('path');
const fs = require('fs');
const fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname));
const Bluebird = require('bluebird');
// current client
var client = null;
let client = null;
module.exports = {
create: function create(apiVersion, port, host, cb) {
@ -24,8 +24,8 @@ module.exports = {
doCreateClient({
logConfig: null
}, function () {
var attemptsRemaining = 60;
var timeout = 500;
let attemptsRemaining = 60;
const timeout = 500;
(function ping() {
client.info({
@ -59,7 +59,7 @@ module.exports = {
options = {};
}
var logConfig = {};
let logConfig = {};
if (_.has(options, 'logConfig')) {
logConfig = options.logConfig;
} else {

View File

@ -1,18 +1,18 @@
module.exports = function (branch) {
var path = require('path');
var jsYaml = require('js-yaml');
var YamlFile = require('./yaml_file');
var root = require('find-root')(__dirname);
var rootReq = function (loc) { return require(path.join(root, loc)); };
var _ = rootReq('src/lib/utils');
var utils = rootReq('grunt/utils');
var es = rootReq('src/elasticsearch');
var clientManager = require('./client_manager');
const path = require('path');
const jsYaml = require('js-yaml');
const YamlFile = require('./yaml_file');
const root = require('find-root')(__dirname);
const rootReq = function (loc) { return require(path.join(root, loc)); };
const _ = rootReq('src/lib/utils');
const utils = rootReq('grunt/utils');
const es = rootReq('src/elasticsearch');
const clientManager = require('./client_manager');
var port = parseInt(process.env.ES_PORT || 9200, 10);
var host = process.env.ES_HOST || 'localhost';
var _release = branch.match(/^v(\d+\.\d+)\.\d+$/);
var apiVersion = _release ? _release[1] : branch;
const port = parseInt(process.env.ES_PORT || 9200, 10);
const host = process.env.ES_HOST || 'localhost';
const _release = branch.match(/^v(\d+\.\d+)\.\d+$/);
const apiVersion = _release ? _release[1] : branch;
console.log(' branch:', branch);
console.log(' port:', port);
@ -32,7 +32,7 @@ module.exports = function (branch) {
return clientManager.get().clearEs();
});
var files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) {
const files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) {
return new YamlFile(filename, docs);
});

View File

@ -9,39 +9,39 @@
*/
module.exports = YamlDoc;
var _ = require('lodash');
var expect = require('expect.js');
var clientManager = require('./client_manager');
var inspect = require('util').inspect;
const _ = require('lodash');
const expect = require('expect.js');
const clientManager = require('./client_manager');
const inspect = require('util').inspect;
var implementedFeatures = ['gtelte', 'regex', 'benchmark', 'stash_in_path', 'groovy_scripting'];
const implementedFeatures = ['gtelte', 'regex', 'benchmark', 'stash_in_path', 'groovy_scripting'];
/**
* The version that ES is running, in comparable string form XXX-XXX-XXX, fetched when needed
* @type {String}
*/
var ES_VERSION = null;
let ES_VERSION = null;
// core expression for finding a version
var versionExp = '((?:\\d+\\.){0,2}\\d+)(?:[\\.\\-]\\w+)?|';
const versionExp = '((?:\\d+\\.){0,2}\\d+)(?:[\\.\\-]\\w+)?|';
// match all whitespace within a "regexp" match arg
var reWhitespaceRE = /\s+/g;
const reWhitespaceRE = /\s+/g;
// match all comments within a "regexp" match arg
var reCommentsRE = /([\S\s]?)#[^\n]*\n/g;
const reCommentsRE = /([\S\s]?)#[^\n]*\n/g;
/**
* Regular Expression to extract a version number from a string
* @type {RegExp}
*/
var versionRE = new RegExp('^(?:' + versionExp + ')$');
const versionRE = new RegExp('^(?:' + versionExp + ')$');
/**
* Regular Expression to extract a version range from a string
* @type {RegExp}
*/
var versionRangeRE = new RegExp('^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$');
const versionRangeRE = new RegExp('^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$');
/**
* Fetches the client.info, and parses out the version number to a comparable string
@ -70,7 +70,7 @@ function versionToComparableString(version, def) {
return def;
}
var parts = _.map(version.split('.'), function (part) {
const parts = _.map(version.split('.'), function (part) {
part = '' + _.parseInt(part);
return (new Array(Math.max(4 - part.length, 0))).join('0') + part;
});
@ -106,7 +106,7 @@ function rangeMatchesCurrentVersion(rangeString, done) {
function YamlDoc(doc, file) {
var self = this;
const self = this;
self.file = file;
self.description = _.keys(doc).shift();
@ -116,7 +116,7 @@ function YamlDoc(doc, file) {
// setup the actions, creating a bound and testable method for each
self._actions = _.map(self.flattenTestActions(doc[self.description]), function (action) {
// get the method that will do the action
var method = self['do_' + action.name];
const method = self['do_' + action.name];
// check that it's a function
expect(method || 'YamlDoc#' + action.name).to.be.a('function');
@ -175,14 +175,14 @@ function YamlDoc(doc, file) {
YamlDoc.compareRangeToVersion = function (range, version) {
expect(range).to.match(versionRangeRE);
var rangeMatch = versionRangeRE.exec(range);
const rangeMatch = versionRangeRE.exec(range);
expect(version).to.match(versionRE);
var versionMatch = versionRE.exec(version);
const versionMatch = versionRE.exec(version);
var min = versionToComparableString(rangeMatch[1], -Infinity);
var max = versionToComparableString(rangeMatch[2], Infinity);
var comp = versionToComparableString(versionMatch[1], Infinity);
const min = versionToComparableString(rangeMatch[1], -Infinity);
const max = versionToComparableString(rangeMatch[2], Infinity);
const comp = versionToComparableString(versionMatch[1], Infinity);
return (min === -Infinity || min <= comp) && (max === Infinity || max >= comp);
};
@ -199,7 +199,7 @@ YamlDoc.prototype = {
flattenTestActions: function (config) {
// creates [ [ {name:"", args:"" }, ... ], ... ]
// from [ {name:args, name:args}, {name:args} ]
var actionSets = _.map(config, function (set) {
const actionSets = _.map(config, function (set) {
return _.map(_.toPairs(set), function (pair) {
return { name: pair[0], args: pair[1] };
});
@ -219,7 +219,7 @@ YamlDoc.prototype = {
* @return {undefined}
*/
each: function (ittr) {
for (var i = 0; i < this._actions.length; i++) {
for (let i = 0; i < this._actions.length; i++) {
if (ittr(this._actions[i].testable, this._actions[i].name) === false) {
break;
}
@ -249,9 +249,9 @@ YamlDoc.prototype = {
* @return {*} - The value requested, or undefined if it was not found
*/
get: function (path, from) {
var self = this;
var log = process.env.LOG_GETS && !from ? console.log.bind(console) : function () {};
var i;
const self = this;
const log = process.env.LOG_GETS && !from ? console.log.bind(console) : function () {};
let i;
if (path === '$body') {
// shortcut, the test just wants the whole body
@ -273,10 +273,10 @@ YamlDoc.prototype = {
log('getting', path, 'from', from);
var steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) {
const steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) {
return step.replace(/\uffff/g, '.');
});
var remainingSteps;
let remainingSteps;
for (i = 0; from != null && i < steps.length; i++) {
if (from[steps[i]] === void 0) {
@ -319,8 +319,8 @@ YamlDoc.prototype = {
}
if (args.features) {
var features = Array.isArray(args.features) ? args.features : [args.features];
var notImplemented = _.difference(features, implementedFeatures);
const features = Array.isArray(args.features) ? args.features : [args.features];
const notImplemented = _.difference(features, implementedFeatures);
if (notImplemented.length) {
if (this.description === 'setup') {
@ -343,10 +343,10 @@ YamlDoc.prototype = {
* @return {[type]} [description]
*/
do_do: function (args, done) {
var catcher;
let catcher;
if (process.env.LOG_DO) {
var __done = done;
const __done = done;
done = function (err, resp) {
console.log('doing', clientActionName, 'with', params);
console.log('got', resp);
@ -388,7 +388,7 @@ YamlDoc.prototype = {
delete args.catch;
var inputParams = {};
const inputParams = {};
// resolve the headers for a request
if (args.headers) {
@ -396,25 +396,25 @@ YamlDoc.prototype = {
delete args.headers;
}
var otherKeys = _.keys(args);
var action = otherKeys.shift();
const otherKeys = _.keys(args);
const action = otherKeys.shift();
if (otherKeys.length) {
return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', ')));
}
var client = clientManager.get();
const client = clientManager.get();
var clientActionName = _.map(action.split('.'), _.camelCase).join('.');
var clientAction = this.get(clientActionName, client);
const clientAction = this.get(clientActionName, client);
_.assign(inputParams, args[action]);
var params = _.transform(inputParams, _.bind(function (params, val, name) {
var camelName = _.camelCase(name);
const camelName = _.camelCase(name);
// search through the params and url peices to find this param name
var paramName = name;
var spec = clientAction && clientAction.spec;
var knownParam = spec && spec.params && spec.params[camelName];
var knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) {
let paramName = name;
const spec = clientAction && clientAction.spec;
const knownParam = spec && spec.params && spec.params[camelName];
const knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) {
if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) {
return true;
}
@ -447,8 +447,8 @@ YamlDoc.prototype = {
catcher = null;
}
var timeoutId;
var cb = _.bind(function (error, body) {
let timeoutId;
const cb = _.bind(function (error, body) {
this._last_requests_response = body;
clearTimeout(timeoutId);
@ -473,7 +473,7 @@ YamlDoc.prototype = {
done(error);
}, this);
var req = clientAction.call(client, params, cb);
const req = clientAction.call(client, params, cb);
timeoutId = setTimeout(function () {
// request timed out, so we will skip the rest of the tests and continue
req.abort();
@ -507,7 +507,7 @@ YamlDoc.prototype = {
* @return {undefined}
*/
do_is_true: function (path) {
var val = this.get(path);
const val = this.get(path);
try {
expect(Boolean(val)).to.be(true, 'path: ' + path);
} catch (e) {
@ -523,7 +523,7 @@ YamlDoc.prototype = {
* @return {undefined}
*/
do_is_false: function (path) {
var val = this.get(path);
const val = this.get(path);
try {
expect(Boolean(val)).to.be(false, 'path: ' + path);
} catch (e) {
@ -563,7 +563,7 @@ YamlDoc.prototype = {
* @return {undefined}
*/
do_match: function (args) {
var self = this;
const self = this;
// recursively replace all $var within args
_.forOwn(args, function recurse(val, key, lvl) {
@ -579,10 +579,10 @@ YamlDoc.prototype = {
});
_.forOwn(args, _.bind(function (match, path) {
var origMatch = match;
const origMatch = match;
var maybeRE = false;
var usedRE = false;
let maybeRE = false;
let usedRE = false;
if (_.isString(match)) {
// convert the matcher into a compatible string for building a regexp
@ -599,8 +599,8 @@ YamlDoc.prototype = {
// whitespace is represented with \s
.replace(reWhitespaceRE, '');
var startsWithSlash = maybeRE[0] === '/';
var endsWithSlash = maybeRE[maybeRE.length - 1] === '/';
const startsWithSlash = maybeRE[0] === '/';
const endsWithSlash = maybeRE[maybeRE.length - 1] === '/';
if (startsWithSlash && endsWithSlash) {
usedRE = true;
@ -608,8 +608,8 @@ YamlDoc.prototype = {
}
}
var val = this.get(path);
var test = 'eql';
let val = this.get(path);
let test = 'eql';
if (match instanceof RegExp) {
test = 'match';
@ -622,7 +622,7 @@ YamlDoc.prototype = {
try {
expect(val).to[test](match);
} catch (e) {
var msg = [
const msg = [
'\nUnable to match',
inspect(match),
'with the path',

View File

@ -6,13 +6,13 @@
*/
module.exports = YamlFile;
var YamlDoc = require('./yaml_doc');
var clientManager = require('./client_manager');
var _ = require('../../../src/lib/utils');
var async = require('async');
const YamlDoc = require('./yaml_doc');
const clientManager = require('./client_manager');
const _ = require('../../../src/lib/utils');
const async = require('async');
function YamlFile(filename, docs) {
var file = this;
const file = this;
// file level skipping flag
file.skipping = false;

View File

@ -1,22 +1,22 @@
var interceptors = [];
var complete = [];
var MockHttpRequest = require('./browser_http');
var XhrServer = MockHttpRequest.MockHttpServer;
var parseUrl = MockHttpRequest.prototype.parseUri;
var _ = require('lodash');
const interceptors = [];
const complete = [];
const MockHttpRequest = require('./browser_http');
const XhrServer = MockHttpRequest.MockHttpServer;
const parseUrl = MockHttpRequest.prototype.parseUri;
const _ = require('lodash');
var server = new XhrServer(function (request) {
var reqDetails = {
const server = new XhrServer(function (request) {
const reqDetails = {
method: request.method,
host: request.urlParts.host,
path: request.urlParts.relative
};
var response = _.find(interceptors, reqDetails);
const response = _.find(interceptors, reqDetails);
if (response) {
// remove of tick down the times
if (response.times === 1) {
var i = interceptors.indexOf(response);
const i = interceptors.indexOf(response);
complete.push(interceptors.splice(i, 1));
} else {
response.times--;
@ -31,8 +31,8 @@ var server = new XhrServer(function (request) {
server.start();
var mockNock = module.exports = function (url) {
var parsedUrl = parseUrl(url);
var req = {
const parsedUrl = parseUrl(url);
const req = {
method: 'GET',
host: parsedUrl.host,
times: 1

View File

@ -6,9 +6,9 @@
*/
module.exports = MockIncommingMessage;
var sinon = require('sinon');
var util = require('util');
var Readable = require('stream').Readable;
const sinon = require('sinon');
const util = require('util');
let Readable = require('stream').Readable;
if (!Readable) {
Readable = require('events').EventEmitter;

View File

@ -5,9 +5,9 @@
*/
module.exports = MockRequest;
var sinon = require('sinon');
var util = require('util');
var http = require('http');
const sinon = require('sinon');
const util = require('util');
const http = require('http');
function MockRequest() {
sinon.stub(this, 'end');

View File

@ -1,3 +1,3 @@
var nock = require('nock');
const nock = require('nock');
nock.disableNetConnect();
module.exports = nock;

View File

@ -3,9 +3,9 @@
* @type {Constuctor}
*/
var util = require('util');
var MockWritableStream; // defined simply for 0.10+, in detail for older versions
var Writable = require('stream').Writable;
const util = require('util');
let MockWritableStream; // defined simply for 0.10+, in detail for older versions
const Writable = require('stream').Writable;
if (Writable) {
@ -18,7 +18,7 @@ if (Writable) {
util.inherits(MockWritableStream, Writable);
} else {
// Node < 0.10 did not provide a usefull stream abstract
var Stream = require('stream').Stream;
const Stream = require('stream').Stream;
module.exports = MockWritableStream = function (opts) {
Stream.call(this);
this.writable = true;
@ -31,8 +31,8 @@ if (Writable) {
return false;
}
var cb;
if (typeof(arguments[arguments.length - 1]) === 'function') {
let cb;
if (typeof (arguments[arguments.length - 1]) === 'function') {
cb = arguments[arguments.length - 1];
}
@ -42,9 +42,9 @@ if (Writable) {
};
MockWritableStream.prototype.end = function (data, encoding, cb) {
if (typeof(data) === 'function') {
if (typeof (data) === 'function') {
cb = data;
} else if (typeof(encoding) === 'function') {
} else if (typeof (encoding) === 'function') {
cb = encoding;
this.write(data);
} else if (arguments.length > 0) {
@ -54,7 +54,7 @@ if (Writable) {
};
MockWritableStream.prototype.destroy = function (cb) {
var self = this;
const self = this;
if (!this.writable) {
if (cb) {

View File

@ -1,23 +1,23 @@
/* global angular */
var _ = require('lodash');
var expect = require('expect.js');
var Promise = require('bluebird');
var sinon = require('sinon');
const _ = require('lodash');
const expect = require('expect.js');
const Promise = require('bluebird');
const sinon = require('sinon');
describe('Angular esFactory', function () {
before(function () {
require('../../../src/elasticsearch.angular.js');
});
var uuid = (function () { var i = 0; return function () { return ++i; }; }());
var esFactory;
var $http;
var $rootScope;
var $httpBackend;
const uuid = (function () { let i = 0; return function () { return ++i; }; }());
let esFactory;
let $http;
let $rootScope;
let $httpBackend;
function bootstrap(env) {
beforeEach(function () {
var promiseProvider = _.noop;
let promiseProvider = _.noop;
if (env.bluebirdPromises) {
promiseProvider = function ($provide) {
$provide.service('$q', function () {
@ -59,7 +59,7 @@ describe('Angular esFactory', function () {
});
it('returns a new client when it is called', function () {
var client = esFactory({
const client = esFactory({
hosts: null
});
@ -69,10 +69,10 @@ describe('Angular esFactory', function () {
});
it('returns an error created by calling a method incorrectly', function () {
var client = esFactory({ hosts: null });
var err;
const client = esFactory({ hosts: null });
let err;
var prom = client.get().then(function () {
const prom = client.get().then(function () {
throw new Error('expected request to fail');
}, function (err) {
expect(err).to.have.property('message');

View File

@ -1,8 +1,8 @@
var expect = require('expect.js');
var Transport = require('../../../src/lib/transport');
const expect = require('expect.js');
const Transport = require('../../../src/lib/transport');
describe('elasticsearch namespace', function () {
var es = window.elasticsearch;
const es = window.elasticsearch;
it('is defined on the window', function () {
expect(es).to.be.ok();
});
@ -12,7 +12,7 @@ describe('elasticsearch namespace', function () {
});
it('can create a client', function () {
var client = new es.Client({ hosts: null });
const client = new es.Client({ hosts: null });
expect(client).to.have.keys('transport');
expect(client.transport).to.be.a(es.Transport);
client.close();

View File

@ -1,6 +1,6 @@
/* global $ */
var expect = require('expect.js');
var Transport = require('../../../src/lib/transport');
const expect = require('expect.js');
const Transport = require('../../../src/lib/transport');
describe('jQuery.es namespace', function () {
it('is defined on the global jQuery', function () {
@ -12,7 +12,7 @@ describe('jQuery.es namespace', function () {
});
it('can create a client', function () {
var client = new $.es.Client({ hosts: null });
const client = new $.es.Client({ hosts: null });
expect(client).to.have.keys('transport');
expect(client.transport).to.be.a($.es.Transport);
client.close();

View File

@ -1,16 +1,16 @@
module.exports = function (makeLogger) {
var expect = require('expect.js');
var stub = require('../utils/auto_release_stub').make();
var fs = require('fs');
var once = require('events').EventEmitter.prototype.once;
var _ = require('lodash');
const expect = require('expect.js');
const stub = require('../utils/auto_release_stub').make();
const fs = require('fs');
const once = require('events').EventEmitter.prototype.once;
const _ = require('lodash');
describe('buffer flush', function () {
if (require('stream').Writable) {
it('writes everything in the buffer to console.error', function () {
var line = 'This string is written 10 times to create buffered output\n';
const line = 'This string is written 10 times to create buffered output\n';
var exitHandler;
let exitHandler;
stub(process, 'once', function (event, handler) {
if (event === 'exit') {
exitHandler = handler;
@ -18,7 +18,7 @@ module.exports = function (makeLogger) {
once.call(process, event, handler);
});
var logger = makeLogger();
const logger = makeLogger();
// write the line 10 times
_.times(10, function () {
@ -26,7 +26,7 @@ module.exports = function (makeLogger) {
});
// collect everything that is written to fs.appendFileSync
var flushedOutput = '';
let flushedOutput = '';
stub(fs, 'appendFileSync', function (path, str) {
flushedOutput += str;
});
@ -40,7 +40,7 @@ module.exports = function (makeLogger) {
});
} else {
it('does not fall apart with non streams2 streams', function () {
var exitHandler;
let exitHandler;
stub(process, 'once', function (event, handler) {
if (event === 'exit') {
exitHandler = handler;
@ -48,7 +48,7 @@ module.exports = function (makeLogger) {
once.call(process, event, handler);
});
var logger = makeLogger();
const logger = makeLogger();
expect(function () {
// call the event handler

View File

@ -1,4 +1,4 @@
var blanket = require('blanket')({
const blanket = require('blanket')({
pattern: require('path').join(__dirname, '../../src')
});

View File

@ -1,13 +1,13 @@
var expect = require('expect.js');
var Log = require('../../src/lib/log');
var LoggerAbstract = require('../../src/lib/logger');
var TracerLogger = require('../../src/lib/loggers/tracer');
var now = new Date('2013-03-01T00:00:00Z');
var sinon = require('sinon');
const expect = require('expect.js');
const Log = require('../../src/lib/log');
const LoggerAbstract = require('../../src/lib/logger');
const TracerLogger = require('../../src/lib/loggers/tracer');
const now = new Date('2013-03-01T00:00:00Z');
const sinon = require('sinon');
module.exports = function (makeLogger) {
var stub = require('../utils/auto_release_stub').make();
var parent = new Log();
const stub = require('../utils/auto_release_stub').make();
const parent = new Log();
afterEach(function () {
parent.close();
@ -15,7 +15,7 @@ module.exports = function (makeLogger) {
describe('Constuctor', function () {
it('calls setupListeners, passes its new levels', function () {
var logger = makeLogger(parent);
let logger = makeLogger(parent);
stub(logger.constructor.prototype, 'setupListeners');
parent.close();
@ -24,21 +24,21 @@ module.exports = function (makeLogger) {
});
it('listens for the loggers\' "closing" event', function () {
var logger = makeLogger(parent);
const logger = makeLogger(parent);
expect(parent.listenerCount('closing')).to.eql(1);
});
});
describe('listening levels', function () {
it('calls cleanUpListeners when the listeners are being setup', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'cleanUpListeners');
logger.setupListeners([]);
expect(logger.cleanUpListeners).to.have.property('callCount', 1);
});
it('listens to just error when log is explicitly error', function () {
var logger = makeLogger(parent, 'error');
const logger = makeLogger(parent, 'error');
expect(parent.listenerCount('error')).to.eql(1);
expect(parent.listenerCount('warning')).to.eql(0);
expect(parent.listenerCount('info')).to.eql(0);
@ -47,7 +47,7 @@ module.exports = function (makeLogger) {
});
it('listens for all the events when level is "trace"', function () {
var logger = makeLogger(parent, 'trace');
const logger = makeLogger(parent, 'trace');
expect(parent.listenerCount('error')).to.eql(1);
expect(parent.listenerCount('warning')).to.eql(1);
expect(parent.listenerCount('info')).to.eql(1);
@ -56,7 +56,7 @@ module.exports = function (makeLogger) {
});
it('listens for specific events when level is an array', function () {
var logger = makeLogger(parent, ['error', 'trace']);
const logger = makeLogger(parent, ['error', 'trace']);
expect(parent.listenerCount('error')).to.eql(1);
expect(parent.listenerCount('warning')).to.eql(0);
expect(parent.listenerCount('info')).to.eql(0);
@ -65,8 +65,8 @@ module.exports = function (makeLogger) {
});
it('sets the logLevel property to the new levels', function () {
var logger = makeLogger();
var levels = ['error'];
const logger = makeLogger();
let levels = ['error'];
logger.setupListeners(levels);
expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
@ -80,14 +80,14 @@ module.exports = function (makeLogger) {
});
it('rejects listening levels it can not listen to', function () {
var logger = makeLogger();
const logger = makeLogger();
expect(function () {
logger.setupListeners(['scream']);
}).to.throwError(/unable to listen/i);
});
it('emits events because something is listening', function () {
var logger = makeLogger(parent, 'trace');
const logger = makeLogger(parent, 'trace');
stub(parent, 'emit');
parent.error(new Error('error message'));
@ -110,7 +110,7 @@ module.exports = function (makeLogger) {
describe('#timestamp', function () {
it('returns in the right format', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger();
const logger = makeLogger();
expect(logger.timestamp()).to.eql('2013-03-01T00:00:00Z');
});
});
@ -118,7 +118,7 @@ module.exports = function (makeLogger) {
describe('#format', function () {
it('returns a single string with the message indented', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger();
const logger = makeLogger();
expect(logger.format('LABEL', 'MSG')).to.eql(
'LABEL: 2013-03-01T00:00:00Z\n' +
' MSG\n' +
@ -128,7 +128,7 @@ module.exports = function (makeLogger) {
it('properly indents multi-line messages', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger();
const logger = makeLogger();
expect(logger.format('LABEL', 'MSG\nwith\nseveral lines')).to.eql(
'LABEL: 2013-03-01T00:00:00Z\n' +
' MSG\n' +
@ -141,7 +141,7 @@ module.exports = function (makeLogger) {
describe('#onError', function () {
it('uses the Error name when it is not just "Error"', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('TypeError');
});
@ -151,7 +151,7 @@ module.exports = function (makeLogger) {
});
it('uses "ERROR" when the error name is "Error"', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('ERROR');
});
@ -163,7 +163,7 @@ module.exports = function (makeLogger) {
describe('#onWarning', function () {
it('uses the "WARNING" label', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('WARNING');
});
@ -172,7 +172,7 @@ module.exports = function (makeLogger) {
});
it('echos the message', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(msg).to.eql('message');
});
@ -184,7 +184,7 @@ module.exports = function (makeLogger) {
describe('#onInfo', function () {
it('uses the "INFO" label', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('INFO');
});
@ -193,7 +193,7 @@ module.exports = function (makeLogger) {
});
it('echos the message', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(msg).to.eql('message');
});
@ -205,7 +205,7 @@ module.exports = function (makeLogger) {
describe('#onDebug', function () {
it('uses the "DEBUG" label', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('DEBUG');
});
@ -214,7 +214,7 @@ module.exports = function (makeLogger) {
});
it('echos the message', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(msg).to.eql('message');
});
@ -226,7 +226,7 @@ module.exports = function (makeLogger) {
describe('#onTrace', function () {
it('uses the "TRACE" label', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(logger, 'write', function (label, msg) {
expect(label).to.eql('TRACE');
});

View File

@ -1,6 +1,6 @@
require('bluebird').longStackTraces();
var specDir = __dirname + '/specs';
const specDir = __dirname + '/specs';
require('fs').readdirSync(specDir).forEach(function (file) {
require(specDir + '/' + file);
});

View File

@ -1,11 +1,11 @@
describe('Logger Abstract', function () {
var expect = require('expect.js');
var sinon = require('sinon');
var Log = require('../../../src/lib/log');
var LoggerAbstract = require('../../../src/lib/logger');
const expect = require('expect.js');
const sinon = require('sinon');
const Log = require('../../../src/lib/log');
const LoggerAbstract = require('../../../src/lib/logger');
var parentLog;
var stub = require('../../utils/auto_release_stub').make();
let parentLog;
const stub = require('../../utils/auto_release_stub').make();
function makeLogger(parent, levels) {
return new LoggerAbstract(parent || parentLog, {
@ -24,7 +24,7 @@ describe('Logger Abstract', function () {
describe('#write', function () {
it('requires that it is overwritten', function () {
expect(function () {
var logger = makeLogger();
const logger = makeLogger();
logger.write();
}).to.throwError(/overwritten/);
});

View File

@ -1,12 +1,12 @@
describe('Client instances creation', function () {
var stream = require('stream');
var util = require('util');
const stream = require('stream');
const util = require('util');
var es = require('../../../src/elasticsearch');
var apis = require('../../../src/lib/apis');
var expect = require('expect.js');
var stub = require('../../utils/auto_release_stub').make();
var client;
const es = require('../../../src/elasticsearch');
const apis = require('../../../src/lib/apis');
const expect = require('expect.js');
const stub = require('../../utils/auto_release_stub').make();
let client;
describe('', function () {
beforeEach(function () {
@ -18,16 +18,16 @@ describe('Client instances creation', function () {
});
it('throws an error linking to the es module when you try to instanciate the exports', function () {
var Es = es;
const Es = es;
expect(function () {
var c = new Es();
return c
const c = new Es();
return c;
}).to.throwError(/previous "elasticsearch" module/);
});
var pkg = require('../../../package.json');
var def = pkg.config.default_api_branch;
var prev = pkg.config.supported_es_branches[pkg.config.supported_es_branches.indexOf(def) + 1];
const pkg = require('../../../package.json');
const def = pkg.config.default_api_branch;
const prev = pkg.config.supported_es_branches[pkg.config.supported_es_branches.indexOf(def) + 1];
it('inherits the ' + def + ' API by default', function () {
expect(client.bulk).to.be(apis[def].bulk);
@ -44,7 +44,7 @@ describe('Client instances creation', function () {
});
it('closing the client causes it\'s transport to be closed', function () {
var called = false;
let called = false;
client.transport.close = function () {
called = true;
};
@ -72,7 +72,7 @@ describe('Client instances creation', function () {
done();
};
var client = new es.Client({
const client = new es.Client({
log: [
{ type: 'stream', stream: new NullStream() }
]

View File

@ -1,8 +1,8 @@
var ca = require('../../../src/lib/client_action').factory;
var proxy = require('../../../src/lib/client_action').proxyFactory;
var expect = require('expect.js');
var _ = require('lodash');
var Promise = require('bluebird');
const ca = require('../../../src/lib/client_action').factory;
const proxy = require('../../../src/lib/client_action').proxyFactory;
const expect = require('expect.js');
const _ = require('lodash');
const Promise = require('bluebird');
/**
* Creates a simple mock of the client, whose "transport" has a request
@ -60,13 +60,13 @@ function makeClientActionProxy(fn, spec) {
describe('Client Action runner', function () {
var action;
let action;
// used to check that params are not clobbered
var params = (function () {
var _stash = {};
const params = (function () {
let _stash = {};
afterEach(function () { _stash = {}; });
var make = function (params) {
const make = function (params) {
_stash.orig = params;
_stash.copy = _.clone(params);
return params;
@ -92,7 +92,7 @@ describe('Client Action runner', function () {
describe('clientAction::proxy', function () {
it('proxies to the passed function', function () {
var action = makeClientActionProxy(function (params, cb) {
const action = makeClientActionProxy(function (params, cb) {
throw new Error('proxy function called');
});
@ -102,8 +102,8 @@ describe('Client Action runner', function () {
});
it('provides the proper context', function (done) {
var client;
var action = makeClientActionProxy(function (params, cb) {
let client;
const action = makeClientActionProxy(function (params, cb) {
client = this;
process.nextTick(function () {
cb(void 0, params);
@ -117,7 +117,7 @@ describe('Client Action runner', function () {
});
it('handles passing just the callback', function () {
var action = makeClientActionProxy(function (params, cb) {
const action = makeClientActionProxy(function (params, cb) {
expect(_.isObject(params)).to.be.ok();
expect(cb).to.be.a('function');
});
@ -126,7 +126,7 @@ describe('Client Action runner', function () {
});
it('supports a param transformation function', function () {
var action = makeClientActionProxy(function (params, cb) {
const action = makeClientActionProxy(function (params, cb) {
expect(params).to.have.property('transformed');
}, {
transform: function (params) {
@ -138,8 +138,8 @@ describe('Client Action runner', function () {
});
it('returns the proxied function\'s return value', function () {
var football = {};
var action = makeClientActionProxy(function (params, cb) {
const football = {};
const action = makeClientActionProxy(function (params, cb) {
return football;
});
@ -537,7 +537,7 @@ describe('Client Action runner', function () {
});
it('accepts numbers, strings, and dates', function (done) {
var now = new Date();
const now = new Date();
action({
one: '42',
@ -587,7 +587,7 @@ describe('Client Action runner', function () {
describe('passing of control params from spec', function () {
it('passes bulkBody', function (done) {
var action = makeClientAction({
const action = makeClientAction({
bulkBody: true
});
@ -598,7 +598,7 @@ describe('Client Action runner', function () {
});
it('sets castExists when the method in the spec is HEAD', function (done) {
var action = makeClientAction({
const action = makeClientAction({
method: 'HEAD'
});
@ -610,12 +610,12 @@ describe('Client Action runner', function () {
});
describe('body handling', function () {
var action = makeClientAction({
const action = makeClientAction({
needsBody: true
});
it('passed the body when it is set', function (done) {
var body = '{"JSON":"PLEASE"}';
const body = '{"JSON":"PLEASE"}';
action({ body: body }, function (err, params) {
expect(params.body).to.be(body);
@ -635,7 +635,7 @@ describe('Client Action runner', function () {
describe('passing of http method', function () {
it('uppercases and passed the default method', function (done) {
var action = makeClientAction({
const action = makeClientAction({
method: 'POST'
});
@ -646,7 +646,7 @@ describe('Client Action runner', function () {
});
it('uppercases and passed the default method', function (done) {
var action = makeClientAction({
const action = makeClientAction({
method: 'POST'
});
@ -659,7 +659,7 @@ describe('Client Action runner', function () {
describe('passing of ignore param', function () {
it('passes ignore as an array', function (done) {
var action = makeClientAction({});
const action = makeClientAction({});
action({ ignore: 404 }, function (err, params) {
expect(params.ignore).to.eql([404]);
done();
@ -669,7 +669,7 @@ describe('Client Action runner', function () {
describe('passing requestTimeout', function () {
it('passes passes the spec value by default', function (done) {
var action = makeClientAction({
const action = makeClientAction({
requestTimeout: 100
});
@ -680,7 +680,7 @@ describe('Client Action runner', function () {
});
it('passes the provided value', function (done) {
var action = makeClientAction({
const action = makeClientAction({
requestTimeout: 100
});
@ -691,7 +691,7 @@ describe('Client Action runner', function () {
});
it('passes nothing be default', function (done) {
var action = makeClientAction({});
const action = makeClientAction({});
action({}, function (err, params) {
expect(params.requestTimeout).be(void 0);
@ -702,7 +702,7 @@ describe('Client Action runner', function () {
describe('url resolver', function () {
var action = makeClientAction({
const action = makeClientAction({
urls: [
{
fmt: '/<%=index%>/<%=type%>/<%=id%>/<%=thing%>',
@ -767,7 +767,7 @@ describe('Client Action runner', function () {
});
describe('param collection', function () {
var action = makeClientAction({
const action = makeClientAction({
params: {
a: { type: 'list', required: true },
b: { type: 'duration', 'default': '15m' },
@ -853,7 +853,7 @@ describe('Client Action runner', function () {
});
it('does not modify the incoming params object', function () {
var action = makeClientAction({
const action = makeClientAction({
url: {
req: {
index: { type: 'string' }

View File

@ -1,42 +1,42 @@
var ConnectionAbstract = require('../../../src/lib/connection');
var Host = require('../../../src/lib/host');
var sinon = require('sinon');
var expect = require('expect.js');
var _ = require('lodash');
var errors = require('../../../src/lib/errors');
const ConnectionAbstract = require('../../../src/lib/connection');
const Host = require('../../../src/lib/host');
const sinon = require('sinon');
const expect = require('expect.js');
const _ = require('lodash');
const errors = require('../../../src/lib/errors');
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
describe('Connection Abstract', function () {
var host = new Host('localhost:9200');
const host = new Host('localhost:9200');
it('constructs with defaults for host, and bound', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
expect(conn.host).to.be(host);
});
it('requires a valid host', function () {
expect(function () {
var conn = new ConnectionAbstract();
const conn = new ConnectionAbstract();
}).to.throwError(TypeError);
expect(function () {
var conn = new ConnectionAbstract({});
const conn = new ConnectionAbstract({});
}).to.throwError(TypeError);
});
it('required that the request method is overridden', function () {
expect(function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
conn.request();
}).to.throwError(/overwrit/);
});
describe('#ping', function () {
it('accpets just a callback', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
stub(conn, 'request');
var cb = function () {};
const cb = function () {};
conn.ping(cb);
expect(conn.request.callCount).to.eql(1);
expect(conn.request.lastCall.args[0]).to.be.a('object');
@ -44,7 +44,7 @@ describe('Connection Abstract', function () {
});
it('accpets just params', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
stub(conn, 'request');
conn.ping({});
expect(conn.request.callCount).to.eql(1);
@ -53,9 +53,9 @@ describe('Connection Abstract', function () {
});
it('allows overriding the requestTimeout, method, and path', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
stub(conn, 'request');
var params = {
const params = {
method: 'HEAD',
path: '/',
requestTimeout: 10000
@ -67,8 +67,8 @@ describe('Connection Abstract', function () {
});
it('defaults to the pingTimeout in the config', function () {
var conn = new ConnectionAbstract(host, { pingTimeout: 5000 });
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const conn = new ConnectionAbstract(host, { pingTimeout: 5000 });
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
stub(conn, 'request');
@ -80,17 +80,17 @@ describe('Connection Abstract', function () {
});
it('calls it\'s own request method', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
stub(conn, 'request');
conn.ping();
expect(conn.request.callCount).to.eql(1);
});
it('sets a timer for the request', function (done) {
var conn = new ConnectionAbstract(host);
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const conn = new ConnectionAbstract(host);
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var order = 0;
let order = 0;
stub(conn, 'request', function (params, cb) {
setTimeout(function () {
@ -113,10 +113,10 @@ describe('Connection Abstract', function () {
});
});
it('calls the requestAborter if req takes too long', function (done) {
var conn = new ConnectionAbstract(host);
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const conn = new ConnectionAbstract(host);
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var order = 0;
let order = 0;
stub(conn, 'request', function (params, cb) {
setTimeout(function () {
@ -148,8 +148,8 @@ describe('Connection Abstract', function () {
describe('#setStatus', function () {
it('emits the "status set" event with `new`, `old` & `conn` args', function () {
var conn = new ConnectionAbstract(host);
var emitted = false;
const conn = new ConnectionAbstract(host);
let emitted = false;
conn.emit = function (eventName) {
emitted = {
@ -164,7 +164,7 @@ describe('Connection Abstract', function () {
});
it('stores the status in this.status', function () {
var conn = new ConnectionAbstract(host);
const conn = new ConnectionAbstract(host);
conn.setStatus('closed');
expect(conn.status).to.eql('closed');

View File

@ -1,11 +1,11 @@
var ConnectionPool = require('../../../src/lib/connection_pool');
var Host = require('../../../src/lib/host');
var ConnectionAbstract = require('../../../src/lib/connection');
var _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
var expect = require('expect.js');
var sinon = require('sinon');
var stub = require('../../utils/auto_release_stub').make();
const ConnectionPool = require('../../../src/lib/connection_pool');
const Host = require('../../../src/lib/host');
const ConnectionAbstract = require('../../../src/lib/connection');
const _ = require('lodash');
const EventEmitter = require('events').EventEmitter;
const expect = require('expect.js');
const sinon = require('sinon');
const stub = require('../../utils/auto_release_stub').make();
function listenerCount(emitter, event) {
if (EventEmitter.listenerCount) {
@ -19,7 +19,7 @@ function listenerCount(emitter, event) {
describe('Connection Pool', function () {
describe('Adding/Removing/Syncing Connections', function () {
var pool, host, connection, host2, connection2;
let pool, host, connection, host2, connection2;
beforeEach(function () {
pool = new ConnectionPool({});
@ -93,7 +93,7 @@ describe('Connection Pool', function () {
});
describe('Connection selection', function () {
var pool, host, host2;
let pool, host, host2;
beforeEach(function () {
pool = new ConnectionPool({});
@ -135,7 +135,7 @@ describe('Connection Pool', function () {
return list[0];
};
var selected = null;
let selected = null;
pool.select(function (err, selection) {
if (err) { throw err; }
@ -163,20 +163,20 @@ describe('Connection Pool', function () {
describe('Connection selection with no living nodes', function () {
it('should ping all of the dead nodes, in order of oldest timeout, and return the first that\'s okay',
function (done) {
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var pool = new ConnectionPool({
const pool = new ConnectionPool({
deadTimeout: 10000
});
var connections = [
const connections = [
new ConnectionAbstract(new Host('http://localhost:9200')),
new ConnectionAbstract(new Host('http://localhost:9201')),
new ConnectionAbstract(new Host('http://localhost:9202')),
new ConnectionAbstract(new Host('http://localhost:9203'))
];
var pingQueue = _.shuffle(connections);
var expectedSelection = pingQueue[pingQueue.length - 1];
const pingQueue = _.shuffle(connections);
const expectedSelection = pingQueue[pingQueue.length - 1];
_.each(pingQueue, function (conn) {
pool.addConnection(conn);
@ -184,7 +184,7 @@ describe('Connection Pool', function () {
if (typeof params === 'function') {
cb = params;
}
var expectedConn = pingQueue.shift();
const expectedConn = pingQueue.shift();
expect(conn).to.be(expectedConn);
if (pingQueue.length) {
process.nextTick(function () {
@ -211,7 +211,7 @@ describe('Connection Pool', function () {
});
describe('Connection state management', function () {
var pool, host, host2, connection, connection2;
let pool, host, host2, connection, connection2;
beforeEach(function () {
pool = new ConnectionPool({});
@ -243,12 +243,12 @@ describe('Connection Pool', function () {
});
it('clears and resets the timeout when a connection redies', function () {
var clock = sinon.useFakeTimers();
const clock = sinon.useFakeTimers();
stub.autoRelease(clock);
connection.setStatus('dead');
expect(_.size(clock.timers)).to.eql(1);
var id = _(clock.timers).keys().first();
const id = _(clock.timers).keys().first();
// it re-dies
connection.setStatus('dead');
@ -257,8 +257,8 @@ describe('Connection Pool', function () {
});
it('does nothing when a connection is re-alive', function () {
var last = pool._conns.alive[pool._conns.alive.length - 1];
var first = pool._conns.alive[0];
const last = pool._conns.alive[pool._conns.alive.length - 1];
const first = pool._conns.alive[0];
expect(last).to.not.be(first);
@ -286,17 +286,17 @@ describe('Connection Pool', function () {
describe('#getConnections', function () {
it('will return all values from the alive list by default', function () {
var pool = new ConnectionPool({});
const pool = new ConnectionPool({});
pool._conns.alive = new Array(1000);
var length = pool._conns.alive.length;
let length = pool._conns.alive.length;
while (length--) {
pool._conns.alive[length] = length;
}
var result = pool.getConnections();
const result = pool.getConnections();
expect(result.length).to.be(1000);
expect(_.reduce(result, function (sum, num) {
sum += num
sum += num;
return sum;
}, 0)).to.eql(499500);
});
@ -304,14 +304,14 @@ describe('Connection Pool', function () {
describe('#calcDeadTimeout', function () {
it('should be configurable via config.calcDeadTimeout', function () {
var pool = new ConnectionPool({
const pool = new ConnectionPool({
calcDeadTimeout: 'flat'
});
expect(pool.calcDeadTimeout).to.be(ConnectionPool.calcDeadTimeoutOptions.flat);
pool.close();
});
it('"flat" always returns the base timeout', function () {
var pool = new ConnectionPool({
const pool = new ConnectionPool({
calcDeadTimeout: 'flat'
});
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
@ -319,7 +319,7 @@ describe('Connection Pool', function () {
expect(pool.calcDeadTimeout(25, 10000)).to.eql(10000);
});
it('"exponential" always increases the timeout based on the attempts', function () {
var pool = new ConnectionPool({
const pool = new ConnectionPool({
calcDeadTimeout: 'exponential'
});
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
@ -327,7 +327,7 @@ describe('Connection Pool', function () {
expect(pool.calcDeadTimeout(25, 10000)).to.be.greaterThan(10000);
});
it('"exponential" produces predicatable results', function () {
var pool = new ConnectionPool({
const pool = new ConnectionPool({
calcDeadTimeout: 'exponential'
});
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
@ -336,7 +336,7 @@ describe('Connection Pool', function () {
expect(pool.calcDeadTimeout(25, 30000)).to.eql(18e5);
});
it('"exponential" repects config.maxDeadtimeout', function () {
var pool = new ConnectionPool({
const pool = new ConnectionPool({
calcDeadTimeout: 'exponential',
maxDeadTimeout: 10000
});

View File

@ -1,8 +1,8 @@
var Log = require('../../../src/lib/log');
var ConsoleLogger = require('../../../src/lib/loggers/console');
var sinon = require('sinon');
var expect = require('expect.js');
var parentLog;
const Log = require('../../../src/lib/log');
const ConsoleLogger = require('../../../src/lib/loggers/console');
const sinon = require('sinon');
const expect = require('expect.js');
let parentLog;
beforeEach(function () {
parentLog = new Log();
@ -14,24 +14,24 @@ afterEach(function () {
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
const config = {
levels: Log.parseLevels(levels || 'trace')
};
return new ConsoleLogger(parent, config);
}
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
describe('Console Logger', function () {
require('../generic_logger_tests')(makeLogger);
it('checks before using unique logging functions, falls back to #log()', function () {
var _warning = console.warn;
const _warning = console.warn;
console.warn = null;
sinon.stub(console, 'log');
var logger = makeLogger();
const logger = makeLogger();
logger.onWarning('message');
expect(console.log.callCount).to.be(1);

View File

@ -1,12 +1,12 @@
var errors = require('../../../src/lib/errors');
var expect = require('expect.js');
var _ = require('lodash');
const errors = require('../../../src/lib/errors');
const expect = require('expect.js');
const _ = require('lodash');
_.each(errors, function (CustomError, name) {
if (name.charAt(0) !== '_') {
describe(name, function () {
it('extend the ErrorAbstract and Error classes', function () {
var err = new CustomError();
const err = new CustomError();
expect(err).to.be.an(Error);
expect(err).to.be.an(errors._Abstract);
});
@ -16,9 +16,9 @@ _.each(errors, function (CustomError, name) {
describe('Error Abstract', function () {
it('provides a stack property in the browser', function () {
var isBrowser = process.browser;
const isBrowser = process.browser;
process.browser = true;
var err = new errors._Abstract();
const err = new errors._Abstract();
process.browser = isBrowser;
expect(err.stack).to.be.a('string');
@ -27,7 +27,7 @@ describe('Error Abstract', function () {
describe('StatusCodeError', function () {
it('exposes status code as a number', function () {
var err = new errors['404']();
const err = new errors['404']();
expect(err.status).to.be(404);
expect(err.status).to.not.be('404');
});

View File

@ -1,13 +1,13 @@
describe('File Logger', function () {
var Log = require('../../../src/lib/log');
var FileLogger = require('../../../src/lib/loggers/file');
var once = require('events').EventEmitter.prototype.once;
var _ = require('../../../src/lib/utils');
var parentLog;
var logger;
var expect = require('expect.js');
var fs = require('fs');
var stub = require('../../utils/auto_release_stub').make();
const Log = require('../../../src/lib/log');
const FileLogger = require('../../../src/lib/loggers/file');
const once = require('events').EventEmitter.prototype.once;
const _ = require('../../../src/lib/utils');
let parentLog;
let logger;
const expect = require('expect.js');
const fs = require('fs');
const stub = require('../../utils/auto_release_stub').make();
beforeEach(function () {
parentLog = new Log();
@ -36,9 +36,9 @@ describe('File Logger', function () {
describe('buffer flush', function () {
if (require('stream').Writable) {
it('writes everything in the buffer to console.error', function () {
var line = 'This string is written 10 times to create buffered output\n';
const line = 'This string is written 10 times to create buffered output\n';
var exitHandler;
let exitHandler;
stub(process, 'once', function (event, handler) {
if (event === 'exit') {
exitHandler = handler;
@ -46,7 +46,7 @@ describe('File Logger', function () {
once.call(process, event, handler);
});
var logger = makeLogger();
const logger = makeLogger();
// write the line 10 times
_.times(10, function () {
@ -54,7 +54,7 @@ describe('File Logger', function () {
});
// collect everything that is written to fs.appendFileSync
var flushedOutput = '';
let flushedOutput = '';
stub(fs, 'appendFileSync', function (path, str) {
flushedOutput += str;
});
@ -68,7 +68,7 @@ describe('File Logger', function () {
});
} else {
it('does not fall apart with non streams2 streams', function () {
var exitHandler;
let exitHandler;
stub(process, 'once', function (event, handler) {
if (event === 'exit') {
exitHandler = handler;
@ -76,7 +76,7 @@ describe('File Logger', function () {
once.call(process, event, handler);
});
var logger = makeLogger();
const logger = makeLogger();
expect(function () {
// call the event handler

View File

@ -1,10 +1,10 @@
var Host = require('../../../src/lib/host');
var _ = require('lodash');
var expect = require('expect.js');
var url = require('url');
var expectSubObject = require('../../utils/expect_sub_object');
const Host = require('../../../src/lib/host');
const _ = require('lodash');
const expect = require('expect.js');
const url = require('url');
const expectSubObject = require('../../utils/expect_sub_object');
var hostDefaults = {
const hostDefaults = {
protocol: 'http',
host: 'localhost',
port: 9200,
@ -24,20 +24,20 @@ var hostDefaults = {
}
};
var base64 = function (str) {
var buffer = Buffer.from ? Buffer.from(str, 'utf8') : new Buffer(str, 'utf8')
return buffer.toString('base64')
}
const base64 = function (str) {
const buffer = Buffer.from ? Buffer.from(str, 'utf8') : new Buffer(str, 'utf8');
return buffer.toString('base64');
};
describe('Host class', function () {
describe('construction', function () {
it('properly sets the defaults', function () {
var host = new Host();
const host = new Host();
expect(host).to.eql(hostDefaults);
});
it('accepts a string for query', function () {
var host = new Host({ query: 'beep=boop' });
const host = new Host({ query: 'beep=boop' });
expect(host.query).to.eql({
beep: 'boop'
@ -45,15 +45,15 @@ describe('Host class', function () {
});
it('accepts other generic params', function () {
var headers = { 'X-Special-Routing-Header': 'pie' };
var host = new Host({ headers: headers });
const headers = { 'X-Special-Routing-Header': 'pie' };
const host = new Host({ headers: headers });
expect(host.headers).to.eql(headers);
});
describe('from a string', function () {
it('accepts a string for the entire url', function () {
var host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true');
const host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true');
expectSubObject(host, {
protocol: 'http',
@ -67,7 +67,7 @@ describe('Host class', function () {
});
it('uses the default port based on the protocol', function () {
var host;
let host;
host = new Host('https://google.com');
expect(host.port).to.be(443);
@ -82,7 +82,7 @@ describe('Host class', function () {
});
it('parses simple urls properly', function () {
var host;
let host;
host = new Host('localhost');
expect(host.host).to.be('localhost');
@ -108,19 +108,19 @@ describe('Host class', function () {
describe('based on the output from url.parse', function () {
it('might cause weird things to happen', function () {
var parsedUrl = url.parse('pizza.com:888');
const parsedUrl = url.parse('pizza.com:888');
// I imagine most people don't expect
expect(parsedUrl.protocol).to.eql('pizza.com:');
expect(parsedUrl.host).to.eql('888');
var host = new Host(parsedUrl);
const host = new Host(parsedUrl);
expect(host.protocol).to.eql('pizza.com');
expect(host.host).to.eql('888');
});
it('will cause extra properties', function () {
var host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes#section'));
const host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes#section'));
expect(host.protocol).to.eql('https');
expect(host.host).to.eql('pizza.com');
expect(host.port).to.eql(888);
@ -135,13 +135,13 @@ describe('Host class', function () {
});
it('ignores anything that\'s not a string or object-y', function () {
var host = new Host(1234);
const host = new Host(1234);
expect(host).to.eql(hostDefaults);
});
it('defaults auth values from the `httpAuth` setting', function () {
var host = new Host('http://localhost:9200', {
const host = new Host('http://localhost:9200', {
httpAuth: 'username:password'
});
@ -151,7 +151,7 @@ describe('Host class', function () {
describe('#makeUrl', function () {
it('merges parameters', function () {
var host = new Host({
const host = new Host({
path: '/prefix',
query: {
user_id: 123
@ -167,7 +167,7 @@ describe('Host class', function () {
});
it('ensures that path starts with a forward-slash', function () {
var host = new Host();
const host = new Host();
host.path = 'prefix';
expect(host.makeUrl({ path: '/this and that' }))
@ -175,14 +175,14 @@ describe('Host class', function () {
});
it('does not try to prevent double forward-slashes', function () {
var host = new Host({ path: 'prefix/' });
const host = new Host({ path: 'prefix/' });
expect(host.makeUrl({ path: '/this and that' }))
.to.be('http://localhost:9200/prefix//this and that');
});
it('creates proper url without any params', function () {
var host = new Host({});
let host = new Host({});
expect(host.makeUrl()).to.be('http://localhost:9200/');
host = new Host({ host: 'john', port: 80 });
@ -193,7 +193,7 @@ describe('Host class', function () {
});
it('outputs valid relative urls when the host is empty', function () {
var host = new Host({
const host = new Host({
host: false,
path: '/path',
query: { this: 'that' }
@ -205,7 +205,7 @@ describe('Host class', function () {
describe('#toString', function () {
it('produces the same output as makeUrl when it is called without params', function () {
var host = new Host({
const host = new Host({
path: '/pasta',
host: 'google.com'
});
@ -216,7 +216,7 @@ describe('Host class', function () {
describe('#getHeaders', function () {
it('merges the passed in headers with the default headers', function () {
var host = new Host({ headers: { 'Joe-Smith': 'present' } });
const host = new Host({ headers: { 'Joe-Smith': 'present' } });
expect(host.getHeaders({
'John-Smith': 'present'
@ -227,7 +227,7 @@ describe('Host class', function () {
});
it('overrides the default headers with the passed in headers', function () {
var host = new Host({ headers: { 'Joe-Smith': 'present' } });
const host = new Host({ headers: { 'Joe-Smith': 'present' } });
expect(host.getHeaders({
'John-Smith': 'present',
@ -239,7 +239,7 @@ describe('Host class', function () {
});
it('adds Accept-Encoding header when the suggestCompression setting is true', function () {
var host = new Host({ suggestCompression: true });
const host = new Host({ suggestCompression: true });
expect(host.getHeaders()).to.eql({
'Accept-Encoding': 'gzip,deflate'
});

View File

@ -1,32 +1,32 @@
describe('Http Connector', function () {
var _ = require('lodash');
var expect = require('expect.js');
var nock = require('nock');
var sinon = require('sinon');
var util = require('util');
var parseUrl = require('url').parse;
var http = require('http');
var https = require('https');
var AgentKeepAlive = require('agentkeepalive');
const _ = require('lodash');
const expect = require('expect.js');
const nock = require('nock');
const sinon = require('sinon');
const util = require('util');
const parseUrl = require('url').parse;
const http = require('http');
const https = require('https');
const AgentKeepAlive = require('agentkeepalive');
var Host = require('../../../src/lib/host');
var errors = require('../../../src/lib/errors');
var HttpConnection = require('../../../src/lib/connectors/http');
var ConnectionAbstract = require('../../../src/lib/connection');
const Host = require('../../../src/lib/host');
const errors = require('../../../src/lib/errors');
const HttpConnection = require('../../../src/lib/connectors/http');
const ConnectionAbstract = require('../../../src/lib/connection');
var expectSubObject = require('../../utils/expect_sub_object');
var MockRequest = require('../../mocks/request');
var MockIncommingMessage = require('../../mocks/incomming_message');
var zlib = require('zlib');
const expectSubObject = require('../../utils/expect_sub_object');
const MockRequest = require('../../mocks/request');
const MockIncommingMessage = require('../../mocks/incomming_message');
const zlib = require('zlib');
nock.disableNetConnect();
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
function makeStubReqMethod(prep) {
return function (params, cb) {
var req = new MockRequest();
const req = new MockRequest();
if (prep) {
prep(req, params, cb);
}
@ -45,12 +45,12 @@ describe('Http Connector', function () {
describe('Constructor', function () {
it('creates an object that extends ConnectionAbstract', function () {
var con = new HttpConnection(new Host());
const con = new HttpConnection(new Host());
expect(con).to.be.a(ConnectionAbstract);
});
it('sets certain defaults', function () {
var con = new HttpConnection(new Host());
const con = new HttpConnection(new Host());
expect(con.hand).to.be(require('http'));
// con.requestTimeout
@ -62,27 +62,27 @@ describe('Http Connector', function () {
it('expects the host to have a protocol of http or https', function () {
expect(function () {
var con = new HttpConnection(new Host('thrifty://es.com/stuff'));
const con = new HttpConnection(new Host('thrifty://es.com/stuff'));
}).to.throwError(/invalid protocol/i);
});
it('allows defining a custom agent', function () {
var football = {};
var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) });
const football = {};
const con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) });
expect(con.agent).to.be(football);
});
it('allows setting agent to false', function () {
var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) });
const con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) });
expect(con.agent).to.be(false);
});
});
describe('#makeReqParams', function () {
it('properly reads the host object', function () {
var host = new Host('john:dude@pizza.com:9200/pizza/cheese?shrooms=true');
var con = new HttpConnection(host, {});
var reqParams = con.makeReqParams();
const host = new Host('john:dude@pizza.com:9200/pizza/cheese?shrooms=true');
const con = new HttpConnection(host, {});
const reqParams = con.makeReqParams();
expect(reqParams).to.not.have.property('auth');
expect(reqParams).to.eql({
@ -97,13 +97,13 @@ describe('Http Connector', function () {
});
it('merges a query object with the hosts\'', function () {
var con = new HttpConnection(new Host({
const con = new HttpConnection(new Host({
query: {
user_id: 123
}
}));
var reqParams = con.makeReqParams({
const reqParams = con.makeReqParams({
query: {
jvm: 'yes'
}
@ -113,8 +113,8 @@ describe('Http Connector', function () {
});
it('merges the path prefix', function () {
var con = new HttpConnection(new Host('https://google.com/path/prefix/for/user/1'));
var reqParams = con.makeReqParams({
const con = new HttpConnection(new Host('https://google.com/path/prefix/for/user/1'));
const reqParams = con.makeReqParams({
method: 'GET',
path: '/items',
query: {
@ -128,9 +128,9 @@ describe('Http Connector', function () {
});
it('merges the query', function () {
var con = new HttpConnection(new Host('http://google.com/pref-x?userId=12345&token=42069'));
const con = new HttpConnection(new Host('http://google.com/pref-x?userId=12345&token=42069'));
var reqParams = con.makeReqParams({
const reqParams = con.makeReqParams({
method: 'PUT',
path: '/stuff',
query: {
@ -144,9 +144,9 @@ describe('Http Connector', function () {
});
it('Works well with minimum params', function () {
var con = new HttpConnection(new Host('http://google.com'));
const con = new HttpConnection(new Host('http://google.com'));
var reqParams = con.makeReqParams({
const reqParams = con.makeReqParams({
method: 'PUT',
path: '/stuff'
});
@ -170,7 +170,7 @@ describe('Http Connector', function () {
});
it('calls http based on the host', function (done) {
var con = new HttpConnection(new Host('http://google.com'));
const con = new HttpConnection(new Host('http://google.com'));
con.request({}, function () {
expect(http.request.callCount).to.be(1);
expect(https.request.callCount).to.be(0);
@ -180,7 +180,7 @@ describe('Http Connector', function () {
});
it('calls https based on the host', function (done) {
var con = new HttpConnection(new Host('https://google.com'));
const con = new HttpConnection(new Host('https://google.com'));
con.request({}, function () {
expect(http.request.callCount).to.be(0);
expect(https.request.callCount).to.be(1);
@ -190,7 +190,7 @@ describe('Http Connector', function () {
});
it('does not log error events', function (done) {
var con = new HttpConnection(new Host('http://google.com'));
const con = new HttpConnection(new Host('http://google.com'));
stub(con.log, 'error');
stub(con.log, 'trace');
@ -217,7 +217,7 @@ describe('Http Connector', function () {
});
it('logs error events', function (done) {
var con = new HttpConnection(new Host('http://google.com'));
const con = new HttpConnection(new Host('http://google.com'));
stub(con.log, 'error');
@ -238,7 +238,7 @@ describe('Http Connector', function () {
function makeStubReqWithMsgWhichErrorsMidBody(err) {
return makeStubReqMethod(function (req, params, cb) {
process.nextTick(function () {
var incom = new MockIncommingMessage();
const incom = new MockIncommingMessage();
incom.statusCode = 200;
setTimeout(function () {
incom.emit('data', '{ "not json"');
@ -250,7 +250,7 @@ describe('Http Connector', function () {
}
it('does not log errors', function (done) {
var con = new HttpConnection(new Host('https://google.com'));
const con = new HttpConnection(new Host('https://google.com'));
stub(con.log, 'error');
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
@ -261,7 +261,7 @@ describe('Http Connector', function () {
});
it('passes the original error on', function (done) {
var con = new HttpConnection(new Host('https://google.com'));
const con = new HttpConnection(new Host('https://google.com'));
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :(')));
con.request({}, function (err, resp, status) {
@ -272,7 +272,7 @@ describe('Http Connector', function () {
});
it('does not pass the partial body along', function (done) {
var con = new HttpConnection(new Host('https://google.com'));
const con = new HttpConnection(new Host('https://google.com'));
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
con.request({}, function (err, resp, status) {
@ -282,7 +282,7 @@ describe('Http Connector', function () {
});
it('does not pass the status code along', function (done) {
var con = new HttpConnection(new Host('https://google.com'));
const con = new HttpConnection(new Host('https://google.com'));
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
con.request({}, function (err, resp, status) {
@ -294,9 +294,9 @@ describe('Http Connector', function () {
describe('#request\'s responder', function () {
it('collects the whole request body', function (done) {
var server = nock('http://esjs.com:9200');
var con = new HttpConnection(new Host('http://esjs.com:9200'));
var body = '{ "USER": "doc" }';
const server = nock('http://esjs.com:9200');
const con = new HttpConnection(new Host('http://esjs.com:9200'));
const body = '{ "USER": "doc" }';
server
.get('/users/1')
@ -315,13 +315,13 @@ describe('Http Connector', function () {
});
it('collects the whole request body (gzip compressed)', function (done) {
var server = nock('http://esjs.com:9200');
var con = new HttpConnection(new Host('http://esjs.com:9200'));
var elements = [];
for (var i = 0; i < 500; i++) {
const server = nock('http://esjs.com:9200');
const con = new HttpConnection(new Host('http://esjs.com:9200'));
const elements = [];
for (let i = 0; i < 500; i++) {
elements.push({ USER: 'doc' });
}
var body = JSON.stringify(elements);
const body = JSON.stringify(elements);
zlib.gzip(body, function (err, compressedBody) {
server
.get('/users/1')
@ -341,13 +341,13 @@ describe('Http Connector', function () {
});
it('collects the whole request body (deflate compressed)', function (done) {
var server = nock('http://esjs.com:9200');
var con = new HttpConnection(new Host('http://esjs.com:9200'));
var elements = [];
for (var i = 0; i < 500; i++) {
const server = nock('http://esjs.com:9200');
const con = new HttpConnection(new Host('http://esjs.com:9200'));
const elements = [];
for (let i = 0; i < 500; i++) {
elements.push({ USER: 'doc' });
}
var body = JSON.stringify(elements);
const body = JSON.stringify(elements);
zlib.deflate(body, function (err, compressedBody) {
server
.get('/users/1')
@ -367,9 +367,9 @@ describe('Http Connector', function () {
});
it('Can handle decompression errors', function (done) {
var server = nock('http://esjs.com:9200');
var con = new HttpConnection(new Host('http://esjs.com:9200'));
var body = 'blah';
const server = nock('http://esjs.com:9200');
const con = new HttpConnection(new Host('http://esjs.com:9200'));
const body = 'blah';
server
.get('/users/1')
.reply(200, body, { 'Content-Encoding': 'gzip' });
@ -387,9 +387,9 @@ describe('Http Connector', function () {
});
it('Ignores serialization errors', function (done) {
var server = nock('http://esjs.com:9200');
var con = new HttpConnection(new Host('http://esjs.com:9200'));
var body = '{ "USER":';
const server = nock('http://esjs.com:9200');
const con = new HttpConnection(new Host('http://esjs.com:9200'));
const body = '{ "USER":';
// partial body
server
@ -410,9 +410,9 @@ describe('Http Connector', function () {
describe('HTTP specifics', function () {
it('uses TCP no delay', function (done) {
var con = new HttpConnection(new Host('localhost'));
const con = new HttpConnection(new Host('localhost'));
stub(http.ClientRequest.prototype, 'setNoDelay');
var server = nock('http://localhost').get('/').reply(200);
const server = nock('http://localhost').get('/').reply(200);
con.request({}, function (err, resp, status) {
expect(http.ClientRequest.prototype.setNoDelay.callCount).to.eql(1);
@ -423,11 +423,11 @@ describe('Http Connector', function () {
});
it('sets the Content-Length header properly', function (done) {
var con = new HttpConnection(new Host('localhost'));
const con = new HttpConnection(new Host('localhost'));
stub(http.ClientRequest.prototype, 'setHeader');
var server = nock('http://localhost').get('/').reply(200);
const server = nock('http://localhost').get('/').reply(200);
var body = 'pasta and 𝄞';
const body = 'pasta and 𝄞';
expect(body.length).to.eql(12); // nope
expect(Buffer.byteLength(body, 'utf8')).to.eql(14); // yep
@ -441,9 +441,9 @@ describe('Http Connector', function () {
});
it('does not set the Accept-Encoding header by default', function (done) {
var con = new HttpConnection(new Host());
var respBody = 'i should not be encoded';
var server = nock('http://localhost:9200')
const con = new HttpConnection(new Host());
const respBody = 'i should not be encoded';
const server = nock('http://localhost:9200')
.matchHeader('accept-encoding', undefined)
.get('/')
.once()
@ -457,9 +457,9 @@ describe('Http Connector', function () {
});
it('sets the Accept-Encoding header when specified', function (done) {
var con = new HttpConnection(new Host({ suggestCompression: true }));
var respBody = 'i should be encoded';
var server = nock('http://localhost:9200')
const con = new HttpConnection(new Host({ suggestCompression: true }));
const respBody = 'i should be encoded';
const server = nock('http://localhost:9200')
.matchHeader('accept-encoding', 'gzip,deflate')
.get('/')
.once()
@ -476,12 +476,12 @@ describe('Http Connector', function () {
describe('Connection cleanup', function () {
it('destroys any connections created', function (done) {
this.timeout(5 * 60 * 1000);
var cp = require('child_process');
var path = require('path');
var fixture = _.partial(path.join, __dirname, '../../fixtures');
var timeout; // start the timeout once we hear back from the client
const cp = require('child_process');
const path = require('path');
const fixture = _.partial(path.join, __dirname, '../../fixtures');
let timeout; // start the timeout once we hear back from the client
var server = cp.fork(fixture('keepalive_server.js'))
const server = cp.fork(fixture('keepalive_server.js'))
.on('message', function (port) {
client.send(port);
});
@ -507,8 +507,8 @@ describe('Http Connector', function () {
});
it('properly removes all elements from the socket', function () {
var con = new HttpConnection(new Host('localhost'));
var sockets = [
const con = new HttpConnection(new Host('localhost'));
const sockets = [
{ destroy: function () {} },
{ destroy: function () {} },
{ destroy: function () {} },
@ -520,7 +520,7 @@ describe('Http Connector', function () {
{ destroy: function () {} },
{ destroy: function () {} }
];
var name = con.agent.getName(parseUrl('http://localhost/'));
const name = con.agent.getName(parseUrl('http://localhost/'));
con.agent.sockets[name] = sockets;
con.setStatus('closed');
expect(sockets).to.eql([]);

View File

@ -1,8 +1,8 @@
describe('JSON serializer', function () {
var JsonSerializer = require('../../../src/lib/serializers/json');
var expect = require('expect.js');
var sinon = require('sinon');
var stub = require('../../utils/auto_release_stub').make();
const JsonSerializer = require('../../../src/lib/serializers/json');
const expect = require('expect.js');
const sinon = require('sinon');
const stub = require('../../utils/auto_release_stub').make();
function makeSerializer() {
return new JsonSerializer();
@ -10,29 +10,29 @@ describe('JSON serializer', function () {
describe('#serialize', function () {
it('defers to JSON.stringify', function () {
var stub = sinon.stub(JSON, 'stringify');
var ser = makeSerializer();
const stub = sinon.stub(JSON, 'stringify');
const ser = makeSerializer();
ser.serialize({ some: 'object' });
expect(stub.callCount).to.eql(1);
stub.restore();
});
it('does not modify strings', function () {
var ser = makeSerializer();
var thing = 'pretend that I am serialized';
const ser = makeSerializer();
const thing = 'pretend that I am serialized';
expect(ser.serialize(thing)).to.be(thing);
});
it('returns nothing for invalid values', function () {
var ser = makeSerializer();
const ser = makeSerializer();
expect(ser.serialize(null)).to.be(undefined);
expect(ser.serialize(false)).to.be(undefined);
});
it('throws serialization errors', function () {
var ser = makeSerializer();
var thing = { name: 'thing' };
const ser = makeSerializer();
const thing = { name: 'thing' };
thing.self = thing;
expect(function () {
@ -44,46 +44,46 @@ describe('JSON serializer', function () {
describe('#deserialize', function () {
it('defers to JSON.parse', function () {
stub(JSON, 'parse');
var ser = makeSerializer();
const ser = makeSerializer();
ser.deserialize('{ "some": "JSON" }');
expect(JSON.parse.callCount).to.eql(1);
});
it('ignores non string values', function () {
var ser = makeSerializer();
var thing = ['pretend that I am not here'];
const ser = makeSerializer();
const thing = ['pretend that I am not here'];
expect(ser.deserialize(thing)).to.be(undefined);
expect(ser.deserialize(null)).to.be(undefined);
expect(ser.deserialize(false)).to.be(undefined);
});
it('catches serialization errors, returns nothing', function () {
var ser = makeSerializer();
var thing = '{ name: \'thing\' }';
const ser = makeSerializer();
const thing = '{ name: \'thing\' }';
expect(ser.deserialize(thing)).to.be(undefined);
});
});
describe('#bulkBody', function () {
var body = [
const body = [
{ index: 'thing' },
{ document: 'hi' }
];
var bulk = '{"index":"thing"}\n{"document":"hi"}\n';
const bulk = '{"index":"thing"}\n{"document":"hi"}\n';
it('creates a string out of an array of obejcts', function () {
var ser = makeSerializer();
const ser = makeSerializer();
expect(ser.bulkBody(body)).to.eql(bulk);
});
it('adds a newline to the end of strings', function () {
var ser = makeSerializer();
const ser = makeSerializer();
expect(ser.bulkBody(bulk.substr(0, bulk.length - 1))).to.eql(bulk);
});
it('throws an error for anything else', function () {
var ser = makeSerializer();
const ser = makeSerializer();
expect(function () {
ser.bulkBody({});
}).to.throwError();

View File

@ -1,6 +1,6 @@
var Log = require('../../../src/lib/log');
var _ = require('lodash');
var expect = require('expect.js');
const Log = require('../../../src/lib/log');
const _ = require('lodash');
const expect = require('expect.js');
describe('Log class', function () {
describe('::parseLevels', function () {
@ -32,7 +32,7 @@ describe('Log class', function () {
});
describe('#addOutput', function () {
var log;
let log;
Log.loggers.stub = function (log, config) {
this.config = config;
@ -47,7 +47,7 @@ describe('Log class', function () {
});
it('Accepts a config object with `level: "{{level}}"`', function () {
var logger = log.addOutput({
const logger = log.addOutput({
type: 'stub',
level: 'warning'
});
@ -58,7 +58,7 @@ describe('Log class', function () {
});
it('Accepts a config object with `level: ["{{level}}"]`', function () {
var logger = log.addOutput({
const logger = log.addOutput({
type: 'stub',
level: ['warning']
});
@ -70,7 +70,7 @@ describe('Log class', function () {
it('Accepts a config object with `levels: "{{level}}"`', function () {
var logger = log.addOutput({
const logger = log.addOutput({
type: 'stub',
levels: 'warning'
});
@ -81,7 +81,7 @@ describe('Log class', function () {
});
it('Accepts a config object with `levels: ["{{level}}"]`', function () {
var logger = log.addOutput({
const logger = log.addOutput({
type: 'stub',
level: ['warning']
});
@ -100,15 +100,15 @@ describe('Log class', function () {
expect(Log.join([{ foo: 'bar' }])).to.eql('{\n "foo": "bar"\n}\n');
});
it('fully stringifies deeply nested objects', function() {
var object = { foo: { bar: { baz: 'value' } } };
var expected = '{\n "bar": {\n "baz": "value"\n }\n}\n';
it('fully stringifies deeply nested objects', function () {
const object = { foo: { bar: { baz: 'value' } } };
const expected = '{\n "bar": {\n "baz": "value"\n }\n}\n';
expect(Log.join(object)).to.eql(expected);
});
});
describe('instance without any outputs', function () {
var log;
let log;
beforeEach(function () {
log = new Log();
});
@ -128,7 +128,7 @@ describe('Log class', function () {
});
describe('instance without one output listening to all events', function () {
var log, call;
let log, call;
beforeEach(function () {
call = void 0;
log = new Log({
@ -154,7 +154,7 @@ describe('Log class', function () {
});
it('should emit an "error" event with an Error object arg', function () {
var err = new Error('error');
const err = new Error('error');
log.error(err);
expect(call.event).to.eql('error');
expect(call.args[0]).to.be(err);
@ -200,7 +200,7 @@ describe('Log class', function () {
describe('constructor', function () {
it('looks for output config options at config.log', function () {
var log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } });
const log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } });
expect(log.listenerCount('error')).to.eql(1);
expect(log.listenerCount('warning')).to.eql(0);
expect(log.listenerCount('info')).to.eql(0);
@ -209,7 +209,7 @@ describe('Log class', function () {
});
it('accepts a string and treat it as a log level', function () {
var log = new Log({ log: 'error' });
const log = new Log({ log: 'error' });
expect(log.listenerCount('error')).to.eql(1);
expect(log.listenerCount('warning')).to.eql(0);
expect(log.listenerCount('info')).to.eql(0);
@ -218,7 +218,7 @@ describe('Log class', function () {
});
it('accepts an array of strings and treat it as a log level config', function () {
var log = new Log({ log: ['error', 'trace'] });
const log = new Log({ log: ['error', 'trace'] });
expect(log.listenerCount('error')).to.eql(1);
expect(log.listenerCount('warning')).to.eql(0);
expect(log.listenerCount('info')).to.eql(0);
@ -227,7 +227,7 @@ describe('Log class', function () {
});
it('accepts an array of output config objects', function () {
var log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] });
const log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] });
expect(log.listenerCount('error')).to.eql(2);
expect(log.listenerCount('warning')).to.eql(1);
expect(log.listenerCount('info')).to.eql(1);
@ -237,22 +237,22 @@ describe('Log class', function () {
it('rejects numbers and other truthy data-types', function () {
expect(function () {
var log = new Log({ log: 1515 });
const log = new Log({ log: 1515 });
}).to.throwError(/invalid logging output config/i);
expect(function () {
var log = new Log({ log: /regexp/ });
const log = new Log({ log: /regexp/ });
}).to.throwError(/invalid logging output config/i);
expect(function () {
var log = new Log({ log: new Date() });
const log = new Log({ log: new Date() });
}).to.throwError(/invalid logging output config/i);
expect(function () {
var log = new Log({ log: [1515] });
const log = new Log({ log: [1515] });
}).to.throwError(/invalid logging output config/i);
expect(function () {
var log = new Log({ log: [/regexp/] });
const log = new Log({ log: [/regexp/] });
}).to.throwError(/invalid logging output config/i);
expect(function () {
var log = new Log({ log: [new Date()] });
const log = new Log({ log: [new Date()] });
}).to.throwError(/invalid logging output config/i);
});
});

View File

@ -1,11 +1,11 @@
describe('Nodes to host callback', function () {
var callback = require('../../../src/lib/nodes_to_host');
var expect = require('expect.js');
const callback = require('../../../src/lib/nodes_to_host');
const expect = require('expect.js');
var nodes90 = require('../../fixtures/short_node_list.0.90.json');
var nodes10 = require('../../fixtures/short_node_list.1.0.json');
var nodes20 = require('../../fixtures/short_node_list.2.0.json');
var nodes50 = require('../../fixtures/short_node_list.5.0.json');
const nodes90 = require('../../fixtures/short_node_list.0.90.json');
const nodes10 = require('../../fixtures/short_node_list.1.0.json');
const nodes20 = require('../../fixtures/short_node_list.2.0.json');
const nodes50 = require('../../fixtures/short_node_list.5.0.json');
context('0.x style', function () {
it('properly creates host objects', function () {
@ -109,7 +109,7 @@ describe('Nodes to host callback', function () {
it('ignores hosts that don\'t have an http_host property', function () {
var hosts = callback({
const hosts = callback({
node_id: {
not: 'much of a node'
}

View File

@ -1,14 +1,14 @@
describe('Random Selector', function () {
var randomSelector = require('../../../src/lib/selectors/random');
var _ = require('lodash');
var expect = require('expect.js');
const randomSelector = require('../../../src/lib/selectors/random');
const _ = require('lodash');
const expect = require('expect.js');
it('chooses a selection by random', function () {
var log = { a: 0, b: 0, c: 0 };
var choices = _.keys(log);
const log = { a: 0, b: 0, c: 0 };
const choices = _.keys(log);
_.times(1000, function () {
var choice = randomSelector(choices);
const choice = randomSelector(choices);
log[choice]++;
});

View File

@ -1,12 +1,12 @@
describe('Round Robin Selector', function () {
var selector = require('../../../src/lib/selectors/round_robin');
var _ = require('lodash');
var expect = require('expect.js');
const selector = require('../../../src/lib/selectors/round_robin');
const _ = require('lodash');
const expect = require('expect.js');
it('chooses options in order', function () {
var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var expected = _.clone(options);
var selections = [];
const options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const expected = _.clone(options);
const selections = [];
_.times(options.length, function () {
selections.push(selector(options));

View File

@ -1,10 +1,10 @@
describe('Stdio Logger', function () {
var Log = require('../../../src/lib/log');
var StdioLogger = require('../../../src/lib/loggers/stdio');
var expect = require('expect.js');
var sinon = require('sinon');
var parentLog;
const Log = require('../../../src/lib/log');
const StdioLogger = require('../../../src/lib/loggers/stdio');
const expect = require('expect.js');
const sinon = require('sinon');
let parentLog;
beforeEach(function () {
parentLog = new Log();
@ -16,37 +16,37 @@ describe('Stdio Logger', function () {
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
const config = {
levels: Log.parseLevels(levels || 'trace')
};
return new StdioLogger(parent, config);
}
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
require('../generic_logger_tests')(makeLogger);
describe('colorizing', function () {
var chalk = require('chalk');
var now = '2013-01-01T00:00:00Z';
var nowDate = new Date(now);
var nowTime = nowDate.getTime();
var clock;
const chalk = require('chalk');
const now = '2013-01-01T00:00:00Z';
const nowDate = new Date(now);
const nowTime = nowDate.getTime();
let clock;
beforeEach(function () {
stub.autoRelease(sinon.useFakeTimers(nowTime));
});
it('uses colors when it\'s supported', function () {
var logger = makeLogger();
var hasColor = require('chalk').supportsColor;
const logger = makeLogger();
const hasColor = require('chalk').supportsColor;
expect(logger.color).to.be(hasColor);
});
it('obeys the logger.color === false', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(process.stdout, 'write');
var withoutColor = 'Elasticsearch INFO: ' + now + '\n something\n\n';
const withoutColor = 'Elasticsearch INFO: ' + now + '\n something\n\n';
logger.color = false;
logger.onInfo('something');
@ -54,10 +54,10 @@ describe('Stdio Logger', function () {
});
it('obeys the logger.color === true', function () {
var logger = makeLogger();
const logger = makeLogger();
stub(process.stdout, 'write');
var withoutColor = 'Elasticsearch DEBUG: ' + now + '\n be weary\n\n';
const withoutColor = 'Elasticsearch DEBUG: ' + now + '\n be weary\n\n';
logger.color = true;
logger.onDebug('be weary');

View File

@ -1,14 +1,14 @@
describe('Stream Logger', function () {
var Log = require('../../../src/lib/log');
var StreamLogger = require('../../../src/lib/loggers/stream');
var MockWritableStream = require('../../mocks/writable_stream');
var once = require('events').EventEmitter.prototype.once;
var stream = new MockWritableStream();
var _ = require('../../../src/lib/utils');
var expect = require('expect.js');
var parentLog;
const Log = require('../../../src/lib/log');
const StreamLogger = require('../../../src/lib/loggers/stream');
const MockWritableStream = require('../../mocks/writable_stream');
const once = require('events').EventEmitter.prototype.once;
const stream = new MockWritableStream();
const _ = require('../../../src/lib/utils');
const expect = require('expect.js');
let parentLog;
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
beforeEach(function () {
stub(stream, 'write');
@ -24,7 +24,7 @@ describe('Stream Logger', function () {
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
const config = {
levels: Log.parseLevels(levels || 'trace'),
stream: stream
};
@ -36,12 +36,12 @@ describe('Stream Logger', function () {
describe('buffer flush', function () {
if (require('stream').Writable) {
it('writes everything in the buffer to console.error', function () {
var logger = makeLogger();
var line = 'This string is written 10 times to create buffered output\n';
const logger = makeLogger();
const line = 'This string is written 10 times to create buffered output\n';
// get the last handler for process's "exit" event
var exitHandlers = process._events.exit;
var exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers;
const exitHandlers = process._events.exit;
const exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers;
// allow the logger to acctually write to the stream
stream.write.restore();
@ -52,7 +52,7 @@ describe('Stream Logger', function () {
});
// collect everything that is written to console.error
var flushedOutput = '';
let flushedOutput = '';
stub(console, 'error', function (str) {
flushedOutput += str;
});
@ -69,7 +69,7 @@ describe('Stream Logger', function () {
});
} else {
it('does not fall apart with non streams2 streams', function () {
var exitHandler;
let exitHandler;
stub(process, 'once', function (event, handler) {
if (event === 'exit') {
exitHandler = handler;
@ -77,7 +77,7 @@ describe('Stream Logger', function () {
once.call(process, event, handler);
});
var logger = makeLogger();
const logger = makeLogger();
expect(function () {
// call the event handler

View File

@ -1,10 +1,10 @@
describe('Tracer Logger', function () {
var Log = require('../../../src/lib/log');
var TracerLogger = require('../../../src/lib/loggers/tracer');
var sinon = require('sinon');
var expect = require('expect.js');
var parentLog;
const Log = require('../../../src/lib/log');
const TracerLogger = require('../../../src/lib/loggers/tracer');
const sinon = require('sinon');
const expect = require('expect.js');
let parentLog;
beforeEach(function () {
parentLog = new Log();
@ -16,21 +16,21 @@ describe('Tracer Logger', function () {
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
const config = {
levels: Log.parseLevels(levels || 'trace')
};
return new TracerLogger(parent, config);
}
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
// require('../generic_logger_tests')(makeLogger);
describe('#formatTraceMessage', function () {
it('includes the original host', function () {
var logger = makeLogger();
const logger = makeLogger();
var formatted = logger._formatTraceMessage({
const formatted = logger._formatTraceMessage({
method: 'DELETE',
url: 'https://originalHost.com:9522/path/to/thing?qs=100',
body: '{ "yes": true }',
@ -45,7 +45,7 @@ describe('Tracer Logger', function () {
});
describe('#write', function () {
var logger;
let logger;
beforeEach(function () {
logger = makeLogger();
stub(logger.stream, 'write');

View File

@ -1,12 +1,12 @@
var Transport = require('../../../src/lib/transport');
var Host = require('../../../src/lib/host');
var errors = require('../../../src/lib/errors');
const Transport = require('../../../src/lib/transport');
const Host = require('../../../src/lib/host');
const errors = require('../../../src/lib/errors');
var sinon = require('sinon');
var expect = require('expect.js');
var _ = require('lodash');
var nodeList = require('../../fixtures/short_node_list.5.0.json');
var stub = require('../../utils/auto_release_stub').make();
const sinon = require('sinon');
const expect = require('expect.js');
const _ = require('lodash');
const nodeList = require('../../fixtures/short_node_list.5.0.json');
const stub = require('../../utils/auto_release_stub').make();
/**
* Allows the tests call #request() without it doing anything past trying to select
@ -31,7 +31,7 @@ describe('Transport Class', function () {
describe('Constructor', function () {
it('Accepts a log class and intanciates it at this.log', function () {
function CustomLogClass() {}
var trans = new Transport({
const trans = new Transport({
log: CustomLogClass
});
@ -39,7 +39,7 @@ describe('Transport Class', function () {
});
it('Accepts a connection pool class and intanciates it at this.connectionPool', function () {
var trans = new Transport({
const trans = new Transport({
connectionPool: CustomConnectionPool
});
@ -49,7 +49,7 @@ describe('Transport Class', function () {
it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () {
Transport.connectionPools.custom = CustomConnectionPool;
var trans = new Transport({
const trans = new Transport({
connectionPool: 'custom'
});
@ -59,7 +59,7 @@ describe('Transport Class', function () {
it('Throws an error when connectionPool config is set wrong', function () {
expect(function () {
var trans = new Transport({
const trans = new Transport({
connectionPool: 'pasta'
});
}).to.throwError(/invalid connectionpool/i);
@ -67,7 +67,7 @@ describe('Transport Class', function () {
it('calls sniff immediately if sniffOnStart is true', function () {
stub(Transport.prototype, 'sniff');
var trans = new Transport({
const trans = new Transport({
sniffOnStart: true
});
@ -75,16 +75,16 @@ describe('Transport Class', function () {
});
it('schedules a sniff when sniffInterval is set', function () {
var clock = sinon.useFakeTimers('setTimeout');
const clock = sinon.useFakeTimers('setTimeout');
stub.autoRelease(clock);
stub(Transport.prototype, 'sniff');
var trans = new Transport({
const trans = new Transport({
sniffInterval: 25000
});
expect(_.size(clock.timers)).to.eql(1);
var id = _.keys(clock.timers).pop();
const id = _.keys(clock.timers).pop();
clock.tick(25000);
expect(trans.sniff.callCount).to.eql(1);
expect(_.size(clock.timers)).to.eql(1);
@ -94,15 +94,15 @@ describe('Transport Class', function () {
describe('config.sniffedNodesProtocol', function () {
it('Assigns to itself', function () {
var football = {};
var trans = new Transport({
const football = {};
const trans = new Transport({
sniffedNodesProtocol: football
});
expect(trans).to.have.property('sniffedNodesProtocol', football);
});
it('Defaults to null when no hosts given', function () {
var trans = new Transport({
const trans = new Transport({
hosts: []
});
@ -110,7 +110,7 @@ describe('Transport Class', function () {
});
it('Defaults to "http" when a single http host given', function () {
var trans = new Transport({
const trans = new Transport({
hosts: [
new Host({
protocol: 'http'
@ -122,7 +122,7 @@ describe('Transport Class', function () {
});
it('Defaults to "http" when multiple http host given', function () {
var trans = new Transport({
const trans = new Transport({
hosts: [
new Host(),
'http://google.com',
@ -137,7 +137,7 @@ describe('Transport Class', function () {
});
it('Defaults to "https" when a single https host given', function () {
var trans = new Transport({
const trans = new Transport({
host: {
protocol: 'https'
}
@ -147,7 +147,7 @@ describe('Transport Class', function () {
});
it('Defaults to "https" when every seed host uses https', function () {
var trans = new Transport({
const trans = new Transport({
hosts: [
'https://localhost:9200',
new Host({
@ -166,7 +166,7 @@ describe('Transport Class', function () {
describe('host config', function () {
it('rejects non-strings/objects', function () {
expect(function () {
var trans = new Transport({
const trans = new Transport({
host: [
'localhost',
9393
@ -175,7 +175,7 @@ describe('Transport Class', function () {
}).to.throwError(TypeError);
expect(function () {
var trans = new Transport({
const trans = new Transport({
host: [
[9292]
]
@ -185,7 +185,7 @@ describe('Transport Class', function () {
it('accepts the config value on the host: key', function () {
stub(Transport.connectionPools.main.prototype, 'setHosts');
var trans = new Transport({
const trans = new Transport({
host: 'localhost'
});
@ -197,7 +197,7 @@ describe('Transport Class', function () {
it('accepts the config value on the hosts: key', function () {
stub(Transport.connectionPools.main.prototype, 'setHosts');
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -209,8 +209,8 @@ describe('Transport Class', function () {
it('accepts A host object as the config', function () {
stub(Transport.connectionPools.main.prototype, 'setHosts');
var h = new Host('localhost');
var trans = new Transport({
const h = new Host('localhost');
const trans = new Transport({
host: h
});
@ -220,7 +220,7 @@ describe('Transport Class', function () {
it('accepts strings as the config', function () {
stub(Transport.connectionPools.main.prototype, 'setHosts');
var trans = new Transport({
const trans = new Transport({
hosts: [
'localhost:8888',
]
@ -237,7 +237,7 @@ describe('Transport Class', function () {
it('accepts objects as the config', function () {
stub(Transport.connectionPools.main.prototype, 'setHosts');
var trans = new Transport({
const trans = new Transport({
hosts: [
{
protocol: 'https',
@ -262,13 +262,13 @@ describe('Transport Class', function () {
// check that it's getting the suggestCompression setting
stub(Transport.connectionPools.main.prototype, 'setHosts');
var trans = new Transport({
let trans = new Transport({
suggestCompression: true,
hosts: ['localhost:9200']
});
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
var hosts = trans.connectionPool.setHosts.firstCall.args[0];
let hosts = trans.connectionPool.setHosts.firstCall.args[0];
expect(hosts).to.have.length(1);
expect(hosts[0]).to.have.property('suggestCompression', true);
@ -285,20 +285,20 @@ describe('Transport Class', function () {
describe('randomizeHosts options', function () {
it('calls _.shuffle be default', function () {
var _ = require('../../../src/lib/utils');
const _ = require('../../../src/lib/utils');
stub(Transport.connectionPools.main.prototype, 'setHosts');
stub(_, 'shuffle');
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
expect(_.shuffle.callCount).to.eql(1);
});
it('skips the call to _.shuffle when false', function () {
var _ = require('../../../src/lib/utils');
const _ = require('../../../src/lib/utils');
stub(Transport.connectionPools.main.prototype, 'setHosts');
stub(_, 'shuffle');
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost',
randomizeHosts: false
});
@ -310,7 +310,7 @@ describe('Transport Class', function () {
describe('#defer', function () {
it('returns a custom defer object', function () {
var defer = Transport.prototype.defer();
const defer = Transport.prototype.defer();
expect(defer).to.have.property('promise');
expect(defer).to.have.property('resolve');
expect(defer).to.have.property('reject');
@ -319,7 +319,7 @@ describe('Transport Class', function () {
describe('#sniff', function () {
var trans;
let trans;
beforeEach(function () {
trans = new Transport({ suggestCompression: true });
@ -366,7 +366,7 @@ describe('Transport Class', function () {
function (done) {
trans.sniff(function () {
expect(trans.connectionPool.setHosts.callCount).to.eql(1);
var hosts = trans.connectionPool.setHosts.lastCall.args[0];
const hosts = trans.connectionPool.setHosts.lastCall.args[0];
expect(hosts).to.have.length(2);
@ -386,7 +386,7 @@ describe('Transport Class', function () {
// check that it's getting the suggestCompression setting
trans.sniff(function () {
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
var hosts = trans.connectionPool.setHosts.lastCall.args[0];
const hosts = trans.connectionPool.setHosts.lastCall.args[0];
expect(hosts).to.have.length(2);
expect(hosts[0]).to.have.property('suggestCompression', true);
expect(hosts[1]).to.have.property('suggestCompression', true);
@ -423,7 +423,7 @@ describe('Transport Class', function () {
describe('#request', function () {
it('logs when it begins', function (done) {
var trans = new Transport();
const trans = new Transport();
stub(trans.log, 'debug');
stub(trans.connectionPool, 'select', function (cb) {
// simulate "no connections"
@ -437,7 +437,7 @@ describe('Transport Class', function () {
});
it('rejects GET requests with a body (callback)', function (done) {
var trans = new Transport();
const trans = new Transport();
stub(trans.log, 'debug');
stub(trans.connectionPool, 'select', function (cb) {
// simulate "no connections"
@ -454,7 +454,7 @@ describe('Transport Class', function () {
});
it('rejects GET requests with a body (promise)', function (done) {
var trans = new Transport();
const trans = new Transport();
stub(trans.log, 'debug');
stub(trans.connectionPool, 'select', function (cb) {
// simulate "no connections"
@ -475,11 +475,11 @@ describe('Transport Class', function () {
describe('gets a body', function () {
it('serializes it', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
var conn = getConnection(trans);
var body = {
const conn = getConnection(trans);
const body = {
_id: 'simple body',
name: 'ഢധയമബ'
};
@ -495,11 +495,11 @@ describe('Transport Class', function () {
});
});
it('serializes bulk bodies', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
var conn = getConnection(trans);
var body = [
const conn = getConnection(trans);
const body = [
{ _id: 'simple body' },
{ name: 'ഢധയമബ' }
];
@ -522,11 +522,11 @@ describe('Transport Class', function () {
describe('gets a body it cant serialize', function () {
it('throws an error', function () {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
getConnection(trans);
var body = {
const body = {
_id: 'circular body'
};
body.body = body;
@ -541,7 +541,7 @@ describe('Transport Class', function () {
describe('when selecting a connection', function () {
it('logs a warning, and responds with NoConnection when it receives nothing', function (done) {
var trans = new Transport();
const trans = new Transport();
stub(trans.log, 'warning');
trans.request({}, function (err, body, status) {
expect(trans.log.warning.callCount).to.eql(1);
@ -552,7 +552,7 @@ describe('Transport Class', function () {
});
});
it('quits if a sync selector throws an error', function () {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost',
selector: function () {
throw new Error('I am broken');
@ -564,7 +564,7 @@ describe('Transport Class', function () {
});
});
it('quits if gets an error from an async selector', function () {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost',
selector: function (connections, cb) {
process.nextTick(function () {
@ -578,10 +578,10 @@ describe('Transport Class', function () {
});
});
it('calls connection#request once it gets one', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
var conn = getConnection(trans);
const conn = getConnection(trans);
stub(conn, 'request', function () {
done();
@ -595,9 +595,9 @@ describe('Transport Class', function () {
// create a test that checks N retries
function testRetries(retries) {
return function (done) {
var randomSelector = require('../../../src/lib/selectors/random');
var connections;
var attempts = 0;
const randomSelector = require('../../../src/lib/selectors/random');
let connections;
let attempts = 0;
function failRequest(params, cb) {
attempts++;
process.nextTick(function () {
@ -605,7 +605,7 @@ describe('Transport Class', function () {
});
}
var trans = new Transport({
const trans = new Transport({
hosts: _.map(new Array(retries + 1), function (val, i) {
return 'localhost/' + i;
}),
@ -639,24 +639,24 @@ describe('Transport Class', function () {
describe('return value', function () {
it('returns an object with an abort() method when a callback is sent', function () {
var tran = new Transport();
const tran = new Transport();
shortCircuitRequest(tran);
var ret = tran.request({}, _.noop);
const ret = tran.request({}, _.noop);
expect(ret).to.be.a('object');
expect(ret.abort).to.be.a('function');
});
it('the object is a promise when a callback is not suplied', function () {
var tran = new Transport();
const tran = new Transport();
shortCircuitRequest(tran);
var ret = tran.request({});
const ret = tran.request({});
expect(ret.then).to.be.a('function');
expect(ret.abort).to.be.a('function');
ret.then(_.noop, _.noop); // prevent complaining from bluebird
});
it('promise is always pulled from the defer created by this.defer()', function () {
var fakePromise = {};
var origDefer = Transport.prototype.defer;
var tran = new Transport({
const fakePromise = {};
const origDefer = Transport.prototype.defer;
const tran = new Transport({
defer: function () {
return {
resolve: _.noop,
@ -666,7 +666,7 @@ describe('Transport Class', function () {
}
});
shortCircuitRequest(tran);
var ret = tran.request({});
const ret = tran.request({});
Transport.prototype.defer = origDefer;
expect(ret).to.be(fakePromise);
expect(ret.abort).to.be.a('function');
@ -677,7 +677,7 @@ describe('Transport Class', function () {
if (process && process.hasOwnProperty('domain')) {
it('works without a domain', function () {
expect(process.domain).to.be(null);
var tran = new Transport();
const tran = new Transport();
shortCircuitRequest(tran);
tran.request({}, function () {
expect(process.domain).to.be(null);
@ -686,12 +686,12 @@ describe('Transport Class', function () {
it('binds the callback to the correct domain', function () {
expect(process.domain).to.be(null);
var domain = require('domain').create();
const domain = require('domain').create();
domain.run(function () {
var tran = new Transport();
const tran = new Transport();
shortCircuitRequest(tran);
expect(process.domain).not.to.be(null);
var startingDomain = process.domain
const startingDomain = process.domain;
tran.request({}, function () {
expect(process.domain).not.to.be(null);
expect(process.domain).to.be(startingDomain);
@ -704,24 +704,24 @@ describe('Transport Class', function () {
describe('aborting', function () {
it('prevents the request from starting if called in the same tick', function () {
var tran = new Transport({
const tran = new Transport({
host: 'localhost'
});
var con = getConnection(tran);
const con = getConnection(tran);
stub(con, 'request', function () {
throw new Error('Request should not have been called.');
});
var ret = tran.request({});
const ret = tran.request({});
ret.abort();
});
it('calls the function returned by the connector if it has been called', function (done) {
var tran = new Transport({
const tran = new Transport({
host: 'localhost'
});
var con = getConnection(tran);
const con = getConnection(tran);
stub(con, 'request', function () {
process.nextTick(function () {
ret.abort();
@ -734,16 +734,16 @@ describe('Transport Class', function () {
var ret = tran.request({});
});
it('ignores the response from the connection when the connector does not support aborting', function (done) {
var tran = new Transport({
const tran = new Transport({
host: 'localhost'
});
var con = getConnection(tran);
const con = getConnection(tran);
stub(con, 'request', function (params, cb) {
cb();
});
var ret = tran.request({}, function () {
const ret = tran.request({}, function () {
throw new Error('Callback should not have been called.');
});
ret.abort();
@ -753,11 +753,11 @@ describe('Transport Class', function () {
describe('timeout', function () {
it('uses 30 seconds for the default', function () {
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var tran = new Transport({});
const tran = new Transport({});
var prom = tran.request({});
const prom = tran.request({});
// disregard promise, prevent bluebird's warnings
prom.then(_.noop, _.noop);
@ -768,13 +768,13 @@ describe('Transport Class', function () {
});
});
it('inherits the requestTimeout from the transport', function () {
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var tran = new Transport({
const tran = new Transport({
requestTimeout: 5000
});
var prom = tran.request({});
const prom = tran.request({});
// disregard promise, prevent bluebird's warnings
prom.then(_.noop, _.noop);
@ -788,9 +788,9 @@ describe('Transport Class', function () {
_.each([false, 0, null], function (falsy) {
it('skips the timeout when it is ' + falsy, function () {
var clock = sinon.useFakeTimers();
const clock = sinon.useFakeTimers();
stub.autoRelease(clock);
var tran = new Transport({});
const tran = new Transport({});
stub(tran.connectionPool, 'select', function () {});
tran.request({
@ -806,7 +806,7 @@ describe('Transport Class', function () {
describe('#setHosts', function () {
it('accepts strings, host objects, and host configs', function () {
var trans = new Transport({ suggestCompression: true });
const trans = new Transport({ suggestCompression: true });
stub(trans.connectionPool, 'setHosts');
trans.setHosts([
@ -816,7 +816,7 @@ describe('Transport Class', function () {
]);
sinon.assert.calledOnce(trans.connectionPool.setHosts);
var host, hosts = trans.connectionPool.setHosts.firstCall.args[0];
let host, hosts = trans.connectionPool.setHosts.firstCall.args[0];
expect(hosts).to.have.length(3);
@ -842,7 +842,7 @@ describe('Transport Class', function () {
describe('#close', function () {
it('proxies the call to it\'s log and connection pool', function () {
var tran = new Transport();
const tran = new Transport();
stub(tran.connectionPool, 'close');
stub(tran.log, 'close');

View File

@ -1,14 +1,14 @@
var Transport = require('../../../src/lib/transport');
var ConnectionPool = require('../../../src/lib/connection_pool');
var Host = require('../../../src/lib/host');
var errors = require('../../../src/lib/errors');
var expect = require('expect.js');
const Transport = require('../../../src/lib/transport');
const ConnectionPool = require('../../../src/lib/connection_pool');
const Host = require('../../../src/lib/host');
const errors = require('../../../src/lib/errors');
const expect = require('expect.js');
var sinon = require('sinon');
var nock = require('../../mocks/server.js');
var through2 = require('through2');
var _ = require('lodash');
var stub = require('../../utils/auto_release_stub').make();
const sinon = require('sinon');
const nock = require('../../mocks/server.js');
const through2 = require('through2');
const _ = require('lodash');
const stub = require('../../utils/auto_release_stub').make();
/**
* Allows the tests call #request() without it doing anything past trying to select
@ -28,7 +28,7 @@ function getConnection(transport, status) {
describe('Transport + Mock server', function () {
describe('#request', function () {
describe('server responds', function () {
var serverMock;
let serverMock;
before(function () {
serverMock = nock('http://localhost')
@ -79,7 +79,7 @@ describe('Transport + Mock server', function () {
describe('with a 400 status code', function () {
it('passes back a 400/BadRequest error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -98,7 +98,7 @@ describe('Transport + Mock server', function () {
describe('with a 404 status code', function () {
describe('and castExists is set', function () {
it('sends back false', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -115,7 +115,7 @@ describe('Transport + Mock server', function () {
});
describe('and the castExists param is not set', function () {
it('sends back a 404/NotFound error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -134,7 +134,7 @@ describe('Transport + Mock server', function () {
describe('with a 500 status code', function () {
it('passes back a 500/InternalServerError error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -152,7 +152,7 @@ describe('Transport + Mock server', function () {
describe('with a 530 status code', function () {
it('passes back a Generic error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -170,7 +170,7 @@ describe('Transport + Mock server', function () {
describe('with a 200 status code', function () {
describe('and the castExists param is set', function () {
it('sends back true', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -187,7 +187,7 @@ describe('Transport + Mock server', function () {
});
describe('with a partial response body', function () {
it('sends back a serialization error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -203,7 +203,7 @@ describe('Transport + Mock server', function () {
});
describe('with a valid response body', function () {
it('sends back the body and status code with no error', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -222,7 +222,7 @@ describe('Transport + Mock server', function () {
describe('with plain text', function () {
it('notices the content-type header and returns the text', function (done) {
var trans = new Transport({
const trans = new Transport({
hosts: 'localhost'
});
@ -239,13 +239,13 @@ describe('Transport + Mock server', function () {
describe('return value', function () {
it('resolves the promise it with the response body', function (done) {
var serverMock = nock('http://esbox.1.com')
const serverMock = nock('http://esbox.1.com')
.get('/')
.reply(200, {
good: 'day'
});
var tran = new Transport({
const tran = new Transport({
hosts: 'http://esbox.1.com'
});
@ -260,13 +260,13 @@ describe('Transport + Mock server', function () {
describe('timeout', function () {
it('clears the timeout when the request is complete', function () {
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
stub.autoRelease(clock);
var tran = new Transport({
const tran = new Transport({
host: 'http://localhost:9200'
});
var server = nock('http://localhost:9200')
const server = nock('http://localhost:9200')
.get('/')
.reply(200, {
i: 'am here'
@ -282,11 +282,11 @@ describe('Transport + Mock server', function () {
});
it('timeout responds with a requestTimeout error', function (done) {
var tran = new Transport({
const tran = new Transport({
host: 'http://localhost:9200'
});
var server = nock('http://localhost:9200')
const server = nock('http://localhost:9200')
.get('/')
.delay(1000)
.reply(200, {
@ -304,13 +304,13 @@ describe('Transport + Mock server', function () {
describe('sniffOnConnectionFault', function () {
it('schedules a sniff when sniffOnConnectionFault is set and a connection failes', function () {
var clock = sinon.useFakeTimers('setTimeout');
const clock = sinon.useFakeTimers('setTimeout');
stub.autoRelease(clock);
var serverMock = nock('http://esbox.1.com')
const serverMock = nock('http://esbox.1.com')
.get('/')
.reply(200, function () {
var str = through2(function (chunk, enc, cb) {
const str = through2(function (chunk, enc, cb) {
cb(new Error('force error'));
});
@ -324,7 +324,7 @@ describe('Transport + Mock server', function () {
stub(ConnectionPool.prototype, '_onConnectionDied');
stub(Transport.prototype, 'sniff');
var tran = new Transport({
const tran = new Transport({
hosts: 'http://esbox.1.com',
sniffOnConnectionFault: true,
maxRetries: 0
@ -343,7 +343,7 @@ describe('Transport + Mock server', function () {
expect(tran.sniff.callCount).to.eql(0);
expect(_.size(clock.timers)).to.eql(1);
var timeout = _.values(clock.timers).pop();
const timeout = _.values(clock.timers).pop();
timeout.func();
expect(tran.sniff.callCount).to.eql(1);
});

View File

@ -1,7 +1,7 @@
var _ = require('../../../src/lib/utils');
var expect = require('expect.js');
const _ = require('../../../src/lib/utils');
const expect = require('expect.js');
var stub = require('../../utils/auto_release_stub').make();
const stub = require('../../utils/auto_release_stub').make();
describe('Utils', function () {
@ -238,14 +238,14 @@ describe('Utils', function () {
describe('#deepMerge', function () {
it('returns the same object that was passed', function () {
var obj = {
const obj = {
foo: 'bar'
};
expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj);
});
it('concats arrays', function () {
var obj = {
const obj = {
foo: ['bax', 'boz']
};
_.deepMerge(obj, { foo: ['boop'] });
@ -253,7 +253,7 @@ describe('Utils', function () {
});
it('wont merge values of different types', function () {
var obj = {
const obj = {
foo: ['stop', 'foo', 'stahp']
};
_.deepMerge(obj, { foo: 'string' });
@ -261,7 +261,7 @@ describe('Utils', function () {
});
it('works recursively', function () {
var obj = {
const obj = {
foo: 'bar',
bax: {
foo: ['bax', 'boz']
@ -275,8 +275,8 @@ describe('Utils', function () {
describe('#createArray', function () {
it('accepts an array of things and simply returns a copy of it', function () {
var inp = [{ a: 1 }, 'pizza'];
var out = _.createArray(inp);
const inp = [{ a: 1 }, 'pizza'];
const out = _.createArray(inp);
expect(out).to.eql(inp);
expect(out).to.not.be(inp);
});
@ -309,28 +309,28 @@ describe('Utils', function () {
* _.funcEnum(object, key, opts, default);
*/
it('tests if the value at key in object is a function, returns it if so', function () {
var config = {
const config = {
func: function () {}
};
expect(_.funcEnum(config, 'func', {}, 'toString'))
.to.be(config.func);
});
it('tests if the value at key in object is undefined, returns the option at key default if so', function () {
var config = {
const config = {
func: undefined
};
expect(_.funcEnum(config, 'func', {}, 'toString'))
.to.be(Object.prototype.toString);
});
it('tests if the value at key in object is a string, returns the option at that key if so', function () {
var config = {
const config = {
'config key name': 'toString'
};
expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON'))
.to.be('pizza');
});
it('throws an informative error if the selection if invalid', function () {
var config = {
const config = {
'config': 'val'
};
@ -350,15 +350,15 @@ describe('Utils', function () {
describe('#applyArgs', function () {
_.times(10, function (i) {
var method = i > 5 ? 'apply' : 'call';
var argCount = i + 1;
var slice = 1;
const method = i > 5 ? 'apply' : 'call';
const argCount = i + 1;
const slice = 1;
it('uses ' + method + ' with ' + i + ' args', function () {
var func = function () {};
const func = function () {};
stub(func, method);
var args = _.map(new Array(i), function (val, i) { return i; });
const args = _.map(new Array(i), function (val, i) { return i; });
_.applyArgs(func, null, args);
expect(func[method].callCount).to.eql(1);
@ -371,11 +371,11 @@ describe('Utils', function () {
it('slices the arguments properly before calling ' + method + ' with ' + argCount + ' args sliced at ' + slice,
function () {
var func = function () {};
const func = function () {};
stub(func, method);
var args = _.map(new Array(argCount), function (val, i) { return i; });
var expected = args.slice(slice);
const args = _.map(new Array(argCount), function (val, i) { return i; });
const expected = args.slice(slice);
_.applyArgs(func, null, args, slice);
expect(func[method].callCount).to.eql(1);
@ -397,14 +397,14 @@ describe('Utils', function () {
});
if (require('stream').Writable) {
var MockWritableStream = require('../../mocks/writable_stream');
const MockWritableStream = require('../../mocks/writable_stream');
it('ignores empty stream', function () {
var stream = new MockWritableStream();
const stream = new MockWritableStream();
expect(_.getUnwrittenFromStream(stream)).to.be('');
});
it('returns only what is in the buffer', function () {
var stream = new MockWritableStream();
const stream = new MockWritableStream();
stream.write('hot');
stream.write('dog');
expect(_.getUnwrittenFromStream(stream)).to.be('dog');

View File

@ -1,7 +1,7 @@
describe('Yaml Test Reader', function () {
var YamlDoc = require('../../integration/yaml_suite/yaml_doc');
var compare = YamlDoc.compareRangeToVersion;
var expect = require('expect.js');
const YamlDoc = require('../../integration/yaml_suite/yaml_doc');
const compare = YamlDoc.compareRangeToVersion;
const expect = require('expect.js');
describe('version range comparison', function () {
it('supports unbounded ranges', function () {

View File

@ -1,15 +1,15 @@
var sinon = require('sinon');
const sinon = require('sinon');
exports.make = function () {
var log = [];
const log = [];
afterEach(function () {
var stub;
let stub;
while (stub = log.pop()) {
stub.restore();
}
});
var stubber = function () {
const stubber = function () {
log.push(sinon.stub.apply(sinon, arguments));
};

View File

@ -1,5 +1,5 @@
var _ = require('lodash');
var expect = require('expect.js');
const _ = require('lodash');
const expect = require('expect.js');
module.exports = function expectSubObject(obj, subObj) {
_.forOwn(subObj, function (val, prop) {
if (typeof obj[prop] === 'object') {

View File

@ -6,16 +6,16 @@
*/
module.exports = JenkinsReporter;
var Base = require('mocha/lib/reporters/base');
var _ = require('lodash');
var chalk = require('chalk');
var makeJUnitXml = require('./make_j_unit_xml');
var fs = require('fs');
var path = require('path');
var inspect = require('util').inspect;
const Base = require('mocha/lib/reporters/base');
const _ = require('lodash');
const chalk = require('chalk');
const makeJUnitXml = require('./make_j_unit_xml');
const fs = require('fs');
const path = require('path');
const inspect = require('util').inspect;
var log = (function () {
var locked = _.bind(process.stdout.write, process.stdout);
const log = (function () {
const locked = _.bind(process.stdout.write, process.stdout);
return function (str) {
if (typeof str !== 'string') {
str = inspect(str);
@ -24,9 +24,9 @@ var log = (function () {
};
}());
var integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; });
var unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; });
var output;
const integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; });
const unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; });
let output;
if (unit) {
output = path.join(__dirname, '../junit-node-unit.xml');
@ -39,16 +39,16 @@ if (unit) {
function JenkinsReporter(runner) {
Base.call(this, runner);
var stats = this.stats;
var pass = 0;
var pending = 0;
var fail = 0;
var rootSuite = {
const stats = this.stats;
let pass = 0;
let pending = 0;
let fail = 0;
const rootSuite = {
results: [],
suites: []
};
var stack = [rootSuite];
const stack = [rootSuite];
function indt() {
return (new Array(stack.length + 1)).join(' ');
@ -105,7 +105,7 @@ function JenkinsReporter(runner) {
log(chalk.red('x'));
}
var errMsg = void 0;
let errMsg = void 0;
if (test.err) {
errMsg = test.err.stack || test.err.toString();
@ -146,7 +146,7 @@ function JenkinsReporter(runner) {
runner.on('hook end', function (hook) {
if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) {
var result = _.last(stack[0].results);
const result = _.last(stack[0].results);
result.stdout += stack[0].stdout;
result.stderr += stack[0].stderr;
stack[0].stdout = stack[0].stderr = '';
@ -155,10 +155,10 @@ function JenkinsReporter(runner) {
runner.on('end', function () {
restoreStdio();
var xml = makeJUnitXml('node ' + process.version, {
const xml = makeJUnitXml('node ' + process.version, {
stats: stats,
suites: _.map(rootSuite.suites, function removeElements(suite) {
var s = {
const s = {
name: suite.name,
start: suite.start,
time: suite.time || 0,
@ -186,8 +186,8 @@ function JenkinsReporter(runner) {
// overload the write methods on stdout and stderr
['stdout', 'stderr'].forEach(function (name) {
var obj = process[name];
var orig = obj.write;
const obj = process[name];
const orig = obj.write;
obj.write = function (chunk) {
if (stack[0]) {
stack[0][name] = (stack[0][name] || '') + chunk;

View File

@ -24,17 +24,17 @@
*/
module.exports = makeJUnitXml;
var testXml = require('xmlbuilder');
var suites = testXml.create('testsuites');
var suiteCount = 0;
var moment = require('moment');
var _ = require('lodash');
var chalk = require('chalk');
const testXml = require('xmlbuilder');
const suites = testXml.create('testsuites');
let suiteCount = 0;
const moment = require('moment');
const _ = require('lodash');
const chalk = require('chalk');
function makeJUnitXml(runnerName, testDetails) {
_.each(testDetails.suites, function serializeSuite(suiteInfo) {
var suite = suites.ele('testsuite', {
const suite = suites.ele('testsuite', {
package: 'elasticsearch-js',
id: suiteCount++,
name: suiteInfo.name,
@ -47,8 +47,8 @@ function makeJUnitXml(runnerName, testDetails) {
});
_.each(suiteInfo.results, function (testInfo) {
var section;
var integration = false;
let section;
let integration = false;
if (suiteInfo.name.match(/\/.*\.yaml$/)) {
section = suiteInfo.name.split('/').slice(0, -1).join('/').replace(/\./g, '/');
@ -61,7 +61,7 @@ function makeJUnitXml(runnerName, testDetails) {
integration = true;
}
var testcase = suite.ele('testcase', {
const testcase = suite.ele('testcase', {
name: testInfo.name,
time: (testInfo.time || 0) / 1000,
classname: runnerName + (integration ? ' - integration' : '') + '.' + section
@ -93,8 +93,8 @@ function makeJUnitXml(runnerName, testDetails) {
}
function giveOutput(el, info) {
var out = info.stdout.trim();
var err = info.stderr.trim();
const out = info.stdout.trim();
const err = info.stderr.trim();
if (out) {
el.ele('system-out', {}).cdata(chalk.stripColor(out));

View File

@ -1,16 +1,16 @@
/* eslint-disable import/no-unresolved */
var express = require('express');
var http = require('http');
var fs = require('fs');
var _ = require('lodash');
var async = require('async');
var root = require('path').join(__dirname, '../..');
var browserify = require('browserify');
var pkg = require(root + '/package.json');
var unitSpecDir = root + '/test/unit/specs';
var browserBuildsDir = root + '/test/unit/browser_builds';
const express = require('express');
const http = require('http');
const fs = require('fs');
const _ = require('lodash');
const async = require('async');
const root = require('path').join(__dirname, '../..');
const browserify = require('browserify');
const pkg = require(root + '/package.json');
const unitSpecDir = root + '/test/unit/specs';
const browserBuildsDir = root + '/test/unit/browser_builds';
var testFiles = {};
const testFiles = {};
testFiles.unit = _(fs.readdirSync(unitSpecDir))
.difference([
@ -33,12 +33,12 @@ testFiles.build = fs.readdirSync(browserBuildsDir)
return browserBuildsDir + '/' + file;
}
return null
return null;
})
.filter(Boolean);
// generic aliasify instance
var aliasify = require('aliasify').configure({
const aliasify = require('aliasify').configure({
aliases: pkg.browser,
excludeExtensions: 'json',
// verbose: false,
@ -46,7 +46,7 @@ var aliasify = require('aliasify').configure({
});
// queue for bundle requests, two at a time
var bundleQueue = async.queue(function (task, done) {
const bundleQueue = async.queue(function (task, done) {
task(done);
}, 2);
@ -54,16 +54,16 @@ var bundleQueue = async.queue(function (task, done) {
function bundleTests(name) {
return function (req, res, next) {
bundleQueue.push(function (_cb) {
var done = function (err) {
const done = function (err) {
if (err) { return next(err); }
_cb(err);
};
res.set('Content-Type', 'application/javascript');
var b = browserify(testFiles[name]);
const b = browserify(testFiles[name]);
b.transform(aliasify);
var str = b.bundle({
const str = b.bundle({
insertGlobals: true
});
@ -81,7 +81,7 @@ function sendFile(file) {
};
}
var app = express();
const app = express();
app
.use(app.router)

View File

@ -1,5 +1,5 @@
const DefinePlugin = require('webpack/lib/DefinePlugin')
const { ignoreLoader, rel } = require('./lib')
const DefinePlugin = require('webpack/lib/DefinePlugin');
const { ignoreLoader, rel } = require('./lib');
module.exports = {
context: rel('src'),
@ -22,4 +22,4 @@ module.exports = {
'process.env.NODE_ENV': '"production"',
}),
],
}
};

View File

@ -1,5 +1,5 @@
const DefinePlugin = require('webpack/lib/DefinePlugin')
const { ignoreLoader, rel } = require('./lib')
const DefinePlugin = require('webpack/lib/DefinePlugin');
const { ignoreLoader, rel } = require('./lib');
module.exports = {
context: rel('src'),
@ -23,4 +23,4 @@ module.exports = {
'process.env.NODE_ENV': '"production"',
}),
],
}
};

View File

@ -1,5 +1,5 @@
const DefinePlugin = require('webpack/lib/DefinePlugin')
const { ignoreLoader, rel } = require('./lib')
const DefinePlugin = require('webpack/lib/DefinePlugin');
const { ignoreLoader, rel } = require('./lib');
module.exports = {
context: rel('src'),
@ -22,4 +22,4 @@ module.exports = {
'process.env.NODE_ENV': '"production"',
}),
],
}
};

View File

@ -1,13 +1,13 @@
const rel = require('path').resolve.bind(null, __dirname, '..')
const rel = require('path').resolve.bind(null, __dirname, '..');
function ignoreLoader(ignores) {
return {
loader: 'null-loader',
test(path) {
return ignores.some(ignore => path.includes(ignore))
return ignores.some(ignore => path.includes(ignore));
},
}
};
}
function jsLoader() {
@ -15,7 +15,7 @@ function jsLoader() {
loader: 'babel-loader',
test: /\.js$/,
include: rel('src'),
}
};
}
module.exports = { ignoreLoader, jsLoader, rel }
module.exports = { ignoreLoader, jsLoader, rel };