From 7c1573fb072d5ca7974f6a72f87f99106b4b8272 Mon Sep 17 00:00:00 2001 From: Spencer Date: Tue, 9 Jul 2019 13:24:13 -0700 Subject: [PATCH] Use standard and prettier (#10) * switch from custom eslint config to standard + prettier * fix new standard eslint violations * add editorconfig file * auto-fix all other violations * update lint yarn script * remove jshint comment --- .editorconfig | 17 + .eslintignore | 3 + .eslintrc | 41 - .eslintrc.js | 13 + .prettierrc | 6 + Gruntfile.js | 19 +- grunt/browser_clients.js | 21 +- grunt/config/aws_s3.js | 10 +- grunt/config/clean.js | 4 +- grunt/config/compress.js | 6 +- grunt/config/concat.js | 28 +- grunt/config/copy.js | 6 +- grunt/config/esvm.js | 63 +- grunt/config/mochacov.js | 38 +- grunt/config/open.js | 4 +- grunt/config/prompt.js | 19 +- grunt/config/run.js | 39 +- grunt/config/saucelabs-mocha.js | 18 +- grunt/config/uglify.js | 12 +- grunt/config/watch.js | 12 +- grunt/config/webpack.js | 4 +- grunt/tasks.js | 69 +- grunt/utils.js | 23 +- package.json | 17 +- scripts/Version.js | 33 +- scripts/_spawn.js | 24 +- scripts/ci.js | 258 ++-- scripts/eslint.js | 2 + scripts/generate/api_index.js | 33 +- scripts/generate/configuration_docs.js | 7 +- scripts/generate/doc_index.js | 22 +- scripts/generate/index.js | 236 ++-- scripts/generate/js_api.js | 249 ++-- scripts/generate/overrides.js | 143 +- scripts/generate/templates/index.js | 54 +- scripts/generate/yaml_tests.js | 26 +- scripts/release/bower.js | 49 +- src/elasticsearch.angular.js | 14 +- src/elasticsearch.jquery.js | 7 +- src/elasticsearch.js | 8 +- src/lib/client.js | 66 +- src/lib/client_action.js | 159 ++- src/lib/connection.js | 39 +- src/lib/connection_pool.js | 93 +- src/lib/connectors/angular.js | 38 +- src/lib/connectors/browser_index.js | 4 +- src/lib/connectors/http.js | 53 +- src/lib/connectors/index.js | 2 +- src/lib/connectors/jquery.js | 17 +- src/lib/connectors/xhr.js | 40 +- src/lib/errors.js | 74 +- src/lib/host.js | 67 +- src/lib/log.js | 98 +- src/lib/logger.js | 104 +- src/lib/loggers/browser_index.js | 2 +- src/lib/loggers/console.js | 14 +- src/lib/loggers/file.js | 4 +- src/lib/loggers/index.js | 2 +- src/lib/loggers/stdio.js | 28 +- src/lib/loggers/stream.js | 12 +- src/lib/loggers/tracer.js | 39 +- src/lib/nodes_to_host.js | 97 +- src/lib/selectors/index.js | 2 +- src/lib/selectors/round_robin.js | 2 +- src/lib/serializers/angular.js | 4 +- src/lib/serializers/index.js | 2 +- src/lib/serializers/json.js | 15 +- src/lib/transport.js | 179 ++- src/lib/transport/find_common_protocol.js | 2 +- .../transport/sniff_on_connection_fault.js | 11 +- src/lib/utils.js | 79 +- test/fixtures/keepalive.js | 78 +- test/fixtures/keepalive_server.js | 6 +- test/integration/yaml_suite/client_manager.js | 148 ++- test/integration/yaml_suite/run.js | 22 +- test/integration/yaml_suite/yaml_doc.js | 500 ++++--- test/integration/yaml_suite/yaml_file.js | 35 +- test/mocks/browser_server.js | 32 +- test/mocks/incomming_message.js | 2 +- test/mocks/writable_stream.js | 22 +- test/unit/browser_builds/angular.js | 53 +- test/unit/browser_builds/generic.js | 8 +- test/unit/browser_builds/jquery.js | 15 +- test/unit/buffer_flush_tests.js | 26 +- test/unit/coverage.js | 2 +- test/unit/generic_logger_tests.js | 118 +- test/unit/index.js | 11 +- test/unit/specs/abstract_logger.js | 15 +- test/unit/specs/client.js | 46 +- test/unit/specs/client_action.js | 1172 ++++++++++------- test/unit/specs/connection_abstract.js | 88 +- test/unit/specs/connection_pool.js | 159 +-- test/unit/specs/console_logger.js | 12 +- test/unit/specs/errors.js | 14 +- test/unit/specs/file_logger.js | 29 +- test/unit/specs/host.js | 148 ++- test/unit/specs/http_connector.js | 409 +++--- test/unit/specs/json_serializer.js | 47 +- test/unit/specs/log.js | 135 +- test/unit/specs/nodes_to_host_callback.js | 76 +- test/unit/specs/random_selector.js | 15 +- test/unit/specs/round_robin_selector.js | 6 +- test/unit/specs/stdio_logger.js | 24 +- test/unit/specs/stream_logger.js | 30 +- test/unit/specs/tracer_logger.js | 33 +- test/unit/specs/transport.js | 503 +++---- test/unit/specs/transport_with_server.js | 447 ++++--- test/unit/specs/utils.js | 266 ++-- test/unit/specs/yaml_test_reader.js | 8 +- test/utils/auto_release_stub.js | 13 +- test/utils/expect_sub_object.js | 7 +- test/utils/jenkins-reporter.js | 92 +- test/utils/make_j_unit_xml.js | 18 +- test/utils/server.js | 64 +- test/utils/slk.js | 10 +- webpack_config/angular.js | 6 +- webpack_config/browser.js | 10 +- webpack_config/jquery.js | 6 +- webpack_config/lib.js | 36 +- 119 files changed, 4506 insertions(+), 3521 deletions(-) create mode 100644 .editorconfig delete mode 100644 .eslintrc create mode 100644 .eslintrc.js create mode 100644 .prettierrc create mode 100644 scripts/eslint.js diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..295765bbd --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[package.json] +insert_final_newline = false + +[*.{md,asciidoc}] +trim_trailing_whitespace = false +insert_final_newline = false \ No newline at end of file diff --git a/.eslintignore b/.eslintignore index 164c685ac..533e38d93 100644 --- a/.eslintignore +++ b/.eslintignore @@ -3,3 +3,6 @@ src/bower_es_js src/lib/apis docs bower_components +!.eslintrc.js +dist +node_modules \ No newline at end of file diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 78c7e38af..000000000 --- a/.eslintrc +++ /dev/null @@ -1,41 +0,0 @@ ---- -extends: "@spalger/personal/es6" - -env: - node: true - -rules: - comma-dangle: off - semi: off - func-names: off - no-var: off - vars-on-top: off - new-cap: off - global-require: off - no-param-reassign: off - padded-blocks: off - brace-style: off - consistent-return: off - default-case: off - dot-notation: off - eqeqeq: warn - max-len: off - no-cond-assign: off - no-console: off - no-else-return: off - no-empty: off - no-restricted-syntax: warn - no-shadow: warn - no-undef: warn - no-underscore-dangle: off - no-unused-expressions: error - no-unused-vars: error - no-use-before-define: off - object-shorthand: off - one-var: off - one-var-declaration-per-line: off - prefer-arrow-callback: off - prefer-rest-params: off - prefer-template: off - quote-props: off - yoda: off diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..7bd41ccdc --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,13 @@ +module.exports = { + extends: ['standard', 'eslint-config-prettier'], + plugins: ['eslint-plugin-prettier'], + rules: { + 'prettier/prettier': 'error', + + // disable standard style-based rules, that's prettiers job + 'standard/computed-property-even-spacing': 'off', + 'node/no-deprecated-api': 'off', + 'standard/no-callback-literal': 'off', + 'handle-callback-err': 'off', + }, +}; diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..1dc716459 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "trailingComma": "es5", + "tabWidth": 2, + "semi": true, + "singleQuote": true +} \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js index ef986ba9f..a4a039547 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,19 +1,22 @@ -module.exports = function (grunt) { +const { resolve } = require('path'); + +module.exports = function(grunt) { // load plugins require('load-grunt-config')(grunt, { - configPath: __dirname + '/grunt/config', + configPath: resolve(__dirname, 'grunt/config'), init: true, config: { - distDir: __dirname + '/dist', - bowerSubmodule: __dirname + '/src/bower_es_js', + distDir: resolve(__dirname, 'dist'), + bowerSubmodule: resolve(__dirname, 'src/bower_es_js'), meta: { - banner: '/*! <%= package.name %> - v<%= package.version %> - ' + + banner: + '/*! <%= package.name %> - v<%= package.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= package.homepage ? " * " + package.homepage + "\\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= package.author.company %>;' + - ' Licensed <%= package.license %> */\n' - } - } + ' Licensed <%= package.license %> */\n', + }, + }, }); // load task definitions diff --git a/grunt/browser_clients.js b/grunt/browser_clients.js index 153ef96b4..734ce71c2 100644 --- a/grunt/browser_clients.js +++ b/grunt/browser_clients.js @@ -1,16 +1,15 @@ -module.exports = function (grunt) { - +module.exports = function(grunt) { grunt.registerTask('browser_clients:dev', [ - 'run:browser_test_server:keepalive' + 'run:browser_test_server:keepalive', ]); grunt.registerTask('browser_clients:test', [ 'browser_clients:build', 'run:browser_test_server', - 'saucelabs-mocha:all' + 'saucelabs-mocha:all', ]); - grunt.registerTask('browser_clients:build', function () { + grunt.registerTask('browser_clients:build', function() { // prevent this from running more than once accidentally grunt.task.renameTask('browser_clients:build', 'browser_clients:rebuild'); grunt.task.registerTask('browser_clients:build', []); @@ -28,7 +27,7 @@ module.exports = function (grunt) { grunt.registerTask('browser_clients:distribute', [ 'browser_clients:build', - '_upload_archive:master' + '_upload_archive:master', ]); grunt.registerTask('browser_clients:release', [ @@ -39,7 +38,7 @@ module.exports = function (grunt) { 'run:clone_bower_repo', 'run:checkout_bower_repo_master', 'copy:dist_to_bower', - 'run:release_bower_tag' + 'run:release_bower_tag', ]); grunt.registerTask('browser_clients:push_prerelease', [ @@ -47,21 +46,21 @@ module.exports = function (grunt) { 'run:clone_bower_repo', 'run:checkout_bower_repo_prerelease', 'copy:dist_to_bower', - 'run:push_prerelease_branch' + 'run:push_prerelease_branch', ]); - grunt.registerTask('_upload_archive', function (type) { + grunt.registerTask('_upload_archive', function(type) { this.requires(['browser_clients:build']); grunt.task.run([ 'copy:dist_to_named_dir', 'compress:' + type + '_zip', 'compress:' + type + '_tarball', - 'aws_s3:upload_archives' + 'aws_s3:upload_archives', ]); }); - grunt.registerTask('_check_for_confirmation', function () { + grunt.registerTask('_check_for_confirmation', function() { if (grunt.config.get('confirm.release')) { grunt.log.verbose.writeln('release confirmed'); } else { diff --git a/grunt/config/aws_s3.js b/grunt/config/aws_s3.js index 76258ce0f..6ceb6117b 100644 --- a/grunt/config/aws_s3.js +++ b/grunt/config/aws_s3.js @@ -5,7 +5,7 @@ module.exports = { expand: true, cwd: '<%= distDir %>/archives', src: '*', - dest: 'elasticsearch/elasticsearch-js/' + dest: 'elasticsearch/elasticsearch-js/', }, ], options: { @@ -14,8 +14,8 @@ module.exports = { bucket: 'download.elasticsearch.org', access: 'public-read', params: { - 'ContentDisposition': 'attachment' - } - } - } + ContentDisposition: 'attachment', + }, + }, + }, }; diff --git a/grunt/config/clean.js b/grunt/config/clean.js index 5eee123b8..e7c0006d0 100644 --- a/grunt/config/clean.js +++ b/grunt/config/clean.js @@ -1,5 +1,5 @@ module.exports = { dist: { - src: ['<%= distDir %>'] - } + src: ['<%= distDir %>'], + }, }; diff --git a/grunt/config/compress.js b/grunt/config/compress.js index 4298f1070..22e243779 100644 --- a/grunt/config/compress.js +++ b/grunt/config/compress.js @@ -5,8 +5,8 @@ function archive(out) { src: 'elasticsearch-js/*', expand: true, options: { - archive: '<%= distDir %>/archives/' + out - } + archive: '<%= distDir %>/archives/' + out, + }, }; } @@ -14,5 +14,5 @@ module.exports = { master_zip: archive('elasticsearch-js-master.zip'), master_tarball: archive('elasticsearch-js-master.tar.gz'), release_zip: archive('elasticsearch-js-<%= package.version %>.zip'), - release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz') + release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz'), }; diff --git a/grunt/config/concat.js b/grunt/config/concat.js index b9434bd38..cb545e07c 100644 --- a/grunt/config/concat.js +++ b/grunt/config/concat.js @@ -1,18 +1,24 @@ module.exports = { dist_banners: { files: { - '<%= distDir %>/elasticsearch.angular.js': '<%= distDir %>/elasticsearch.angular.js', - '<%= distDir %>/elasticsearch.angular.min.js': '<%= distDir %>/elasticsearch.angular.min.js', - '<%= distDir %>/elasticsearch.jquery.js': '<%= distDir %>/elasticsearch.jquery.js', - '<%= distDir %>/elasticsearch.jquery.min.js': '<%= distDir %>/elasticsearch.jquery.min.js', + '<%= distDir %>/elasticsearch.angular.js': + '<%= distDir %>/elasticsearch.angular.js', + '<%= distDir %>/elasticsearch.angular.min.js': + '<%= distDir %>/elasticsearch.angular.min.js', + '<%= distDir %>/elasticsearch.jquery.js': + '<%= distDir %>/elasticsearch.jquery.js', + '<%= distDir %>/elasticsearch.jquery.min.js': + '<%= distDir %>/elasticsearch.jquery.min.js', '<%= distDir %>/elasticsearch.js': '<%= distDir %>/elasticsearch.js', - '<%= distDir %>/elasticsearch.min.js': '<%= distDir %>/elasticsearch.min.js' + '<%= distDir %>/elasticsearch.min.js': + '<%= distDir %>/elasticsearch.min.js', }, options: { - banner: '<%= meta.banner %>\n' + - ';(function () {\n' + - '/* prevent lodash from detecting external amd loaders */var define; \n', - footer: '\n}());' - } - } + banner: + '<%= meta.banner %>\n' + + ';(function () {\n' + + '/* prevent lodash from detecting external amd loaders */var define; \n', + footer: '\n}());', + }, + }, }; diff --git a/grunt/config/copy.js b/grunt/config/copy.js index 8ae070ea7..89b192bbc 100644 --- a/grunt/config/copy.js +++ b/grunt/config/copy.js @@ -3,12 +3,12 @@ module.exports = { cwd: '<%= distDir %>', src: '*.js', dest: '<%= distDir %>/elasticsearch-js/', - expand: true + expand: true, }, dist_to_bower: { cwd: '<%= distDir %>', src: '*.js', dest: '<%= bowerSubmodule %>', - expand: true - } + expand: true, + }, }; diff --git a/grunt/config/esvm.js b/grunt/config/esvm.js index d67cca51f..5f45cfa2c 100644 --- a/grunt/config/esvm.js +++ b/grunt/config/esvm.js @@ -21,96 +21,93 @@ var versionedOpts = [ 'cluster.name': 'elasticsearch_js_test_runners', 'http.port': port, 'network.host': host, - 'discovery.zen.minimum_master_nodes': 1 - } + 'discovery.zen.minimum_master_nodes': 1, + }, }, { version: '<3', config: { - 'discovery.zen.ping.multicast.enabled': false - } + 'discovery.zen.ping.multicast.enabled': false, + }, }, { version: '<1.6', config: { - 'discovery.zen.ping_timeout': 1 - } + 'discovery.zen.ping_timeout': 1, + }, }, { version: '^1.2 <1.6', config: { 'node.bench': true, - 'script.disable_dynamic': false - } + 'script.disable_dynamic': false, + }, }, { version: '>=1.6 <5.0', config: { - 'node.bench': true - } + 'node.bench': true, + }, }, { version: '>2.0 <5.0', config: { - 'node.testattr': 'test' - } + 'node.testattr': 'test', + }, }, { version: '>=5.0', config: { - 'node.attr.testattr': 'test' - } + 'node.attr.testattr': 'test', + }, }, { version: '>=1.6 <5.0', config: { - 'script.indexed': true - } + 'script.indexed': true, + }, }, { version: '>=1.6', config: { 'script.inline': true, 'path.repo': process.env.ES_PATH_REPO || fromRoot('.es-snapshot-repos'), - 'repositories.url.allowed_urls': 'http://snapshot.*' - } - } + 'repositories.url.allowed_urls': 'http://snapshot.*', + }, + }, ]; // targets for each branch -gruntUtils.branches.forEach(function (branch) { +gruntUtils.branches.forEach(function(branch) { exports[branch] = { options: Version.fromBranch(branch).mergeOpts(versionedOpts, { branch: branch, - fresh: true - }) + fresh: true, + }), }; }); - // ci target, based on env variables -(function () { +(function() { var v; var opts = { config: { - 'http.port': port - } + 'http.port': port, + }, }; if (release) { v = new Version(String(release).replace(/^v/, '')); opts.version = v.version; - } - else if (ref) { - v = new Version.fromBranch(String(ref).replace(/v?(\d+\.\d+)\..+/, '$1')); + } else if (ref) { + v = Version.fromBranch(String(ref).replace(/v?(\d+\.\d+)\..+/, '$1')); opts.branch = ref; opts.fresh = true; - } - else { + } else { return; } exports.ci_env = { - options: v.mergeOpts(versionedOpts, opts) + options: v.mergeOpts(versionedOpts, opts), }; -}()); +})(); diff --git a/grunt/config/mochacov.js b/grunt/config/mochacov.js index aade288a1..6c9a3835d 100644 --- a/grunt/config/mochacov.js +++ b/grunt/config/mochacov.js @@ -1,6 +1,8 @@ var root = require('find-root')(__dirname); var rel = require('path').resolve.bind(null, root); -var rootReq = function (p) { return require(rel(p)); }; +var rootReq = function(p) { + return require(rel(p)); +}; var utils = rootReq('src/lib/utils'); var grunt = require('grunt'); @@ -10,22 +12,22 @@ var config = { unit: { src: 'test/unit/index.js', options: { - reporter: 'nyan' - } + reporter: 'nyan', + }, }, ci_unit: { src: 'test/unit/index.js', options: { - reporter: 'spec' - } + reporter: 'spec', + }, }, jenkins_unit: { src: 'test/unit/index.js', options: { - reporter: JENKINS_REPORTER - } + reporter: JENKINS_REPORTER, + }, }, // run the unit tests, and update coverage.html @@ -33,8 +35,8 @@ var config = { src: 'test/unit/coverage.js', options: { reporter: 'html-cov', - instrument: false - } + instrument: false, + }, }, // for use by travis @@ -43,26 +45,26 @@ var config = { options: { reporter: 'mocha-lcov-reporter', coveralls: true, - instrument: false - } + instrument: false, + }, }, integration: { src: null, options: { - reporter: 'spec' - } + reporter: 'spec', + }, }, jenkins_integration: { src: null, options: { - reporter: JENKINS_REPORTER - } - } + reporter: JENKINS_REPORTER, + }, + }, }; -grunt.registerTask('mocha_integration', function (branch) { +grunt.registerTask('mocha_integration', function(branch) { grunt.config.set( 'mochacov.integration.src', 'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js' @@ -70,7 +72,7 @@ grunt.registerTask('mocha_integration', function (branch) { grunt.task.run('mochacov:integration'); }); -grunt.registerTask('mocha_jenkins_integration', function (branch) { +grunt.registerTask('mocha_jenkins_integration', function(branch) { grunt.config.set( 'mochacov.jenkins_integration.src', 'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js' diff --git a/grunt/config/open.js b/grunt/config/open.js index 2043afa59..19e0fbc7f 100644 --- a/grunt/config/open.js +++ b/grunt/config/open.js @@ -1,6 +1,6 @@ module.exports = { coverage: { path: 'coverage.html', - app: 'Google Chrome' - } + app: 'Google Chrome', + }, }; diff --git a/grunt/config/prompt.js b/grunt/config/prompt.js index ba7823c6b..22bb842f4 100644 --- a/grunt/config/prompt.js +++ b/grunt/config/prompt.js @@ -1,12 +1,15 @@ module.exports = { confirm_release: { options: { - questions: [{ - config: 'confirm.release', - type: 'confirm', - message: 'Are you sure you want to overwrite/release version <%= package.version %> of elasticsearch-js', - default: false - }] - } - } + questions: [ + { + config: 'confirm.release', + type: 'confirm', + message: + 'Are you sure you want to overwrite/release version <%= package.version %> of elasticsearch-js', + default: false, + }, + ], + }, + }, }; diff --git a/grunt/config/run.js b/grunt/config/run.js index 6f60eb15e..0b03412a8 100644 --- a/grunt/config/run.js +++ b/grunt/config/run.js @@ -4,57 +4,56 @@ var config = { generate: { exec: 'node ./scripts/generate/index.js', options: { - passArgs: [ - 'verbose' - ] - } + passArgs: ['verbose'], + }, }, browser_test_server: { exec: 'node ./test/utils/server', options: { wait: false, quiet: false, - ready: /listening/ - } + ready: /listening/, + }, }, clone_bower_repo: { exec: [ 'test -d src/bower_es_js', - 'git clone git@github.com:elastic/bower-elasticsearch-js.git <%= bowerSubmodule %>' + 'git clone git@github.com:elastic/bower-elasticsearch-js.git <%= bowerSubmodule %>', ].join(' || '), options: { - quiet: true - } + quiet: true, + }, }, checkout_bower_repo_master: { exec: 'git checkout master', options: { cwd: '<%= bowerSubmodule %>', - quiet: true - } + quiet: true, + }, }, checkout_bower_repo_prerelease: { exec: 'git checkout prerelease', options: { cwd: '<%= bowerSubmodule %>', - quiet: true - } + quiet: true, + }, }, push_prerelease_branch: { - exec: 'git add -A && git commit -m "prerelease build" && git push origin prerelease', + exec: + 'git add -A && git commit -m "prerelease build" && git push origin prerelease', options: { cwd: '<%= bowerSubmodule %>', - quite: true - } + quite: true, + }, }, release_bower_tag: { - exec: 'node ./scripts/release/bower' - } + exec: 'node ./scripts/release/bower', + }, }; -gruntUtils.branches.forEach(function (branch) { +gruntUtils.branches.forEach(function(branch) { config['generate_' + branch] = { - exec: 'node ./scripts/generate/index.js --branch=' + branch + exec: 'node ./scripts/generate/index.js --branch=' + branch, }; }); diff --git a/grunt/config/saucelabs-mocha.js b/grunt/config/saucelabs-mocha.js index 54b681983..3496d8cbb 100644 --- a/grunt/config/saucelabs-mocha.js +++ b/grunt/config/saucelabs-mocha.js @@ -4,7 +4,7 @@ module.exports = { options: { urls: [ 'http://127.0.0.1:8000/unit.html', - 'http://127.0.0.1:8000/builds.html' + 'http://127.0.0.1:8000/builds.html', ], testname: 'es.js client tests', build: process.env.TRAVIS_BUILD_ID, @@ -14,23 +14,23 @@ module.exports = { browsers: [ { browserName: 'googlechrome', - platform: 'XP' + platform: 'XP', }, { browserName: 'firefox', - platform: 'Linux' + platform: 'Linux', }, { browserName: 'internet explorer', version: '11', - platform: 'Windows 8.1' + platform: 'Windows 8.1', }, { browserName: 'internet explorer', version: '10', - platform: 'Windows 8' - } - ] - } - } + platform: 'Windows 8', + }, + ], + }, + }, }; diff --git a/grunt/config/uglify.js b/grunt/config/uglify.js index d2c587044..c6f12bf81 100644 --- a/grunt/config/uglify.js +++ b/grunt/config/uglify.js @@ -2,12 +2,14 @@ module.exports = { dist: { files: { '<%= distDir %>/elasticsearch.min.js': '<%= distDir %>/elasticsearch.js', - '<%= distDir %>/elasticsearch.angular.min.js': '<%= distDir %>/elasticsearch.angular.js', - '<%= distDir %>/elasticsearch.jquery.min.js': '<%= distDir %>/elasticsearch.jquery.js' + '<%= distDir %>/elasticsearch.angular.min.js': + '<%= distDir %>/elasticsearch.angular.js', + '<%= distDir %>/elasticsearch.jquery.min.js': + '<%= distDir %>/elasticsearch.jquery.js', }, options: { preserveComments: false, - screwIE8: true - } - } + screwIE8: true, + }, + }, }; diff --git a/grunt/config/watch.js b/grunt/config/watch.js index 29fff8ba7..53ef25ab6 100644 --- a/grunt/config/watch.js +++ b/grunt/config/watch.js @@ -4,13 +4,11 @@ module.exports = { 'src/**/*.js', 'grunt/**/*.js', 'test/unit/**/*.js', - 'Gruntfile.js' - ], - tasks: [ - 'mochacov:unit' + 'Gruntfile.js', ], + tasks: ['mochacov:unit'], options: { - interrupt: true - } - } + interrupt: true, + }, + }, }; diff --git a/grunt/config/webpack.js b/grunt/config/webpack.js index 86406ddd8..18e03b1c8 100644 --- a/grunt/config/webpack.js +++ b/grunt/config/webpack.js @@ -3,5 +3,5 @@ module.exports = { require('../../webpack_config/browser'), require('../../webpack_config/angular'), require('../../webpack_config/jquery'), - ] -} + ], +}; diff --git a/grunt/tasks.js b/grunt/tasks.js index 5a10c4e46..fdced78ea 100644 --- a/grunt/tasks.js +++ b/grunt/tasks.js @@ -1,26 +1,23 @@ -module.exports = function (grunt) { +module.exports = function(grunt) { var Promise = require('bluebird'); var gruntUtils = require('./utils'); var readFile = Promise.promisify(require('fs').readFile); var writeFile = Promise.promisify(require('fs').writeFile); - // Default task runs the build process. - grunt.registerTask('default', [ - 'test' - ]); + grunt.registerTask('default', ['test']); - grunt.registerTask('test', function (branch) { + grunt.registerTask('test', function(branch) { var tasks = [ branch ? 'run:generate_' + branch : 'run:generate', - 'mochacov:unit' + 'mochacov:unit', ]; var branches = branch ? [branch] : gruntUtils.branches; process.env.ES_PORT = process.env.ES_PORT || 9400; process.env.ES_HOST = process.env.ES_HOST || 'localhost'; - branches.forEach(function (branch) { + branches.forEach(function(branch) { tasks.push( 'esvm:' + branch, 'mocha_integration:' + branch, @@ -34,10 +31,10 @@ module.exports = function (grunt) { grunt.registerTask('unit_test', 'mochacov:unit'); grunt.registerTask('coverage', [ 'mochacov:make_coverage_html', - 'open:coverage' + 'open:coverage', ]); - grunt.registerTask('version', function (nextVersion) { + grunt.registerTask('version', function(nextVersion) { var root = require('path').join.bind(null, __dirname, '..'); var readmePath = root('README.md'); var packagePath = root('package.json'); @@ -46,35 +43,39 @@ module.exports = function (grunt) { Promise.all([ require(packagePath), readFile(readmePath, 'utf8'), - readFile(browserBuildsPath, 'utf8') + readFile(browserBuildsPath, 'utf8'), ]) - .spread(function (pkg, readme, browserBuilds) { - var current = pkg.version; + .spread(function(pkg, readme, browserBuilds) { + var current = pkg.version; - pkg.version = nextVersion; - browserBuilds = gruntUtils.replaceAll(browserBuilds, current, nextVersion); + pkg.version = nextVersion; + browserBuilds = gruntUtils.replaceAll( + browserBuilds, + current, + nextVersion + ); - readme = gruntUtils.replaceAll(readme, current, nextVersion); + readme = gruntUtils.replaceAll(readme, current, nextVersion); - readme = gruntUtils.replaceAll( - readme, - '/' + gruntUtils.minorVersion(current) + '.svg', - '/' + gruntUtils.minorVersion(nextVersion) + '.svg' - ); + readme = gruntUtils.replaceAll( + readme, + '/' + gruntUtils.minorVersion(current) + '.svg', + '/' + gruntUtils.minorVersion(nextVersion) + '.svg' + ); - readme = gruntUtils.replaceAll( - readme, - 'branch=' + gruntUtils.minorVersion(current), - 'branch=' + gruntUtils.minorVersion(nextVersion) - ); + readme = gruntUtils.replaceAll( + readme, + 'branch=' + gruntUtils.minorVersion(current), + 'branch=' + gruntUtils.minorVersion(nextVersion) + ); - // write all files to disk - return Promise.all([ - writeFile(readmePath, readme), - writeFile(browserBuildsPath, browserBuilds), - writeFile(packagePath, JSON.stringify(pkg, null, ' ')) - ]); - }) - .nodeify(this.async()); + // write all files to disk + return Promise.all([ + writeFile(readmePath, readme), + writeFile(browserBuildsPath, browserBuilds), + writeFile(packagePath, JSON.stringify(pkg, null, ' ')), + ]); + }) + .nodeify(this.async()); }); }; diff --git a/grunt/utils.js b/grunt/utils.js index 660af964a..3ba7967c3 100644 --- a/grunt/utils.js +++ b/grunt/utils.js @@ -7,13 +7,15 @@ var unstable = pkg.config.unstable_es_branches; var branches = [].concat(stable, unstable); var gruntUtils = { - branchSuffix: function (branch) { - return branch === gruntUtils.branches._default ? '' : '_' + utils.snakeCase(branch); + branchSuffix: function(branch) { + return branch === gruntUtils.branches._default + ? '' + : '_' + utils.snakeCase(branch); }, branches: branches, stableBranches: stable, unstableBranches: unstable, - browserBranches: stable.slice(0, 5).concat(unstable) + browserBranches: stable.slice(0, 5).concat(unstable), }; gruntUtils.branches._default = pkg.config.default_api_branch; @@ -21,14 +23,17 @@ gruntUtils.branches._default = pkg.config.default_api_branch; /* * trim down a version id to the minor version number ('1.5.1' => '1.5') */ -gruntUtils.minorVersion = function (version) { - return version.split('.').slice(0, 2).join('.'); +gruntUtils.minorVersion = function(version) { + return version + .split('.') + .slice(0, 2) + .join('.'); }; /* * increment the version based on the release "type" */ -gruntUtils.increaseVersion = function (version, type) { +gruntUtils.increaseVersion = function(version, type) { var i; switch (type) { case 'major': @@ -47,14 +52,14 @@ gruntUtils.increaseVersion = function (version, type) { } // breakout the current version - var next = version.split('.').map(function (n) { + var 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('.'); }; @@ -62,7 +67,7 @@ gruntUtils.increaseVersion = function (version, type) { /* * replace all instances of `replace` with `replacement` without creating a regexp object */ -gruntUtils.replaceAll = function (str, replace, replacement) { +gruntUtils.replaceAll = function(str, replace, replacement) { var out = ''; var remaining = str; var i = 0; diff --git a/package.json b/package.json index 2ece22781..9cbddec40 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "test": "grunt test", "generate": "node scripts/generate", "grunt": "grunt", - "lint": "eslint ." + "lint": "node scripts/eslint" }, "browser": { "./src/lib/connectors/index.js": "./src/lib/connectors/browser_index.js", @@ -46,7 +46,6 @@ "devDependencies": { "@babel/core": "^7.0.0-beta.41", "@babel/preset-env": "^7.0.0-beta.41", - "@spalger/eslint-config-personal": "^0.4.0", "aliasify": "^2.1.0", "async": "~0.8.0", "babel-eslint": "^8.2.2", @@ -55,11 +54,14 @@ "blanket": "^1.2.3", "bluebird": "^2.9.14", "browserify": "^16.1.1", - "eslint": "^2.9.0", - "eslint-config-airbnb": "^8.0.0", - "eslint-plugin-import": "^1.6.1", - "eslint-plugin-jsx-a11y": "^1.0.4", - "eslint-plugin-react": "^5.0.1", + "eslint-config-prettier": "6.0.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.18.0", + "eslint-plugin-node": "9.1.0", + "eslint-plugin-prettier": "3.1.0", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.0", + "eslint": "6.0.1", "expect.js": "^0.3.1", "express": "~3.4.7", "find-root": "~0.1.1", @@ -92,6 +94,7 @@ "null-loader": "^0.1.1", "open": "0.0.5", "optimist": "~0.6.0", + "prettier": "1.18.2", "semver": "^4.3.6", "sinon": "^1.17.4", "split": "~0.3.2", diff --git a/scripts/Version.js b/scripts/Version.js index b3bde3838..328fbc26d 100644 --- a/scripts/Version.js +++ b/scripts/Version.js @@ -1,6 +1,9 @@ var _ = require('lodash'); var pkg = require('../package.json'); -var branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches]; +var branches = [ + ...pkg.config.supported_es_branches, + ...pkg.config.unstable_es_branches, +]; var semver = require('semver'); function nextMajorVersion() { @@ -8,14 +11,19 @@ function nextMajorVersion() { .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) { const largestMinor = branches - .map(v => v.split('.').map(parseFloat).slice(0, 2)) + .map(v => + v + .split('.') + .map(parseFloat) + .slice(0, 2) + ) // ensure all tuples have length 2 .filter(vt => vt.length === 2) // ensure all values in tuples are not NaN @@ -37,38 +45,37 @@ function Version(v) { this.patch = semver.patch(v); } -Version.fromBranch = function (branch) { +Version.fromBranch = function(branch) { // n.m -> n.m.0 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'); }; -Version.prototype.increment = function (which) { +Version.prototype.increment = function(which) { return new Version(semver.inc(this.version, which)); }; -Version.prototype.satisfies = function (range) { +Version.prototype.satisfies = function(range) { return semver.satisfies(this.version, range); }; // merge a list of option objects, each of which has a "version" key dictating // the range of versions those options should be included in. Options are merged // in the order of the array -Version.prototype.mergeOpts = function (versioned, overrides) { - +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; diff --git a/scripts/_spawn.js b/scripts/_spawn.js index 3efdd7d99..a67bed8c3 100644 --- a/scripts/_spawn.js +++ b/scripts/_spawn.js @@ -14,9 +14,12 @@ function indent(line) { function consume(stream) { stream - .pipe(split()) - .pipe(map(indent)) - .pipe(process.stdout, { end: false }); + .pipe(split()) + .pipe(map(indent)) + .pipe( + process.stdout, + { end: false } + ); } function _spawn(cmd, args, opts, cb) { @@ -27,11 +30,7 @@ function _spawn(cmd, args, opts, cb) { } var conf = { - stdio: [ - 'ignore', - opts.verbose ? 'pipe' : 'ignore', - 'pipe' - ] + stdio: ['ignore', opts.verbose ? 'pipe' : 'ignore', 'pipe'], }; var subdir; @@ -41,7 +40,12 @@ function _spawn(cmd, args, opts, cb) { subdir = path.relative(root, opts.cwd); } - console.log(chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + cmd + ' ' + args.join(' ')); + console.log( + chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + + cmd + + ' ' + + args.join(' ') + ); var cp = spawn(cmd, args, conf); @@ -58,6 +62,6 @@ function _spawn(cmd, args, opts, cb) { return cp; } -_spawn.exec = function (cmd, opts, cb) { +_spawn.exec = function(cmd, opts, cb) { return _spawn('/bin/sh', ['-c', cmd], opts, cb); }; diff --git a/scripts/ci.js b/scripts/ci.js index bc6bda3d3..af1625339 100644 --- a/scripts/ci.js +++ b/scripts/ci.js @@ -37,7 +37,7 @@ var TASKS = []; var output; // main output stream var taskOut; // task output stream -task('NODE_UNIT', true, function () { +task('NODE_UNIT', true, function() { if (!JENKINS) { return grunt('mochacov:ci_unit'); } @@ -45,67 +45,77 @@ task('NODE_UNIT', true, function () { return grunt('mochacov:jenkins_unit'); }); -task('NODE_INTEGRATION', true, function () { +task('NODE_INTEGRATION', true, function() { var branch = ENV.ES_REF; - return node('scripts/generate', '--no-api', '--branch', branch) - .then(function () { - var target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch; - return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env'); - }); + return node('scripts/generate', '--no-api', '--branch', branch).then( + function() { + var target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch; + return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env'); + } + ); }); -task('SAUCE_LABS', false, function () { - return new Promise(function (resolve, reject) { +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']; - spawn(GRUNT, serverTasks, function (proc) { + var serverTasks = [ + 'browser_clients:build', + 'run:browser_test_server:keepalive', + ]; + spawn(GRUNT, serverTasks, function(proc) { var toLines = split(); - proc.stdout - .pipe(toLines) - .pipe(through2(function (line, enc, cb) { - cb(); + proc.stdout.pipe(toLines).pipe( + through2(function(line, enc, cb) { + cb(); - if (String(line).indexOf('listening on port 8000') === -1) return; + if (String(line).indexOf('listening on port 8000') === -1) return; + trySaucelabs() + .finally(function() { + if (proc) proc.kill(); + }) + .then(resolve, reject); - trySaucelabs() - .finally(function () { if (proc) proc.kill(); }) - .then(resolve, reject); - - proc.on('exit', function () { proc = null; }); - proc.stdout.unpipe(toLines); - toLines.end(); - })); + proc.on('exit', function() { + proc = null; + }); + proc.stdout.unpipe(toLines); + toLines.end(); + }) + ); }) - // ignore server errors - .catch(_.noop); + // ignore server errors + .catch(_.noop); // attempt to run tests on saucelabs and retry if it fails var saucelabsAttempts = 0; function trySaucelabs() { saucelabsAttempts++; - return new Promise(function (resolve, reject) { + return new Promise(function(resolve, reject) { log(chalk.green('saucelabs attempt #', saucelabsAttempts)); - spawn(GRUNT, ['saucelabs-mocha'], function (cp) { - + spawn(GRUNT, ['saucelabs-mocha'], function(cp) { var failedTests = 0; - cp.stdout - .pipe(split()) - .pipe(map(function (line) { - failedTests += String(line).trim() === 'Passed: false' ? 1 : 0; - })); + cp.stdout.pipe(split()).pipe( + map(function(line) { + failedTests += String(line).trim() === 'Passed: false' ? 1 : 0; + }) + ); cp.on('error', reject); - cp.on('exit', function (code) { + cp.on('exit', function(code) { if (code > 0) { if (failedTests > 0) { return reject(new Error('Browser tests failed')); } if (saucelabsAttempts >= 3) { - return reject(new Error('Saucelabs is like really really down. Tried 3 times')); + return reject( + new Error( + 'Saucelabs is like really really down. Tried 3 times' + ) + ); } log(chalk.blue('trying saucelabs again...')); @@ -115,21 +125,20 @@ task('SAUCE_LABS', false, function () { return resolve(); }); }) - // swallow spawn() errors, custom error handler in place - .catch(_.noop); + // swallow spawn() errors, custom error handler in place + .catch(_.noop); }); } }); }); -task('CHECK_COVERAGE', false, function () { - return grunt('mochacov:ship_coverage') - .catch(function () { - log('FAILED TO SHIP COVERAGE! but that\'s okay'); +task('CHECK_COVERAGE', false, function() { + return grunt('mochacov:ship_coverage').catch(function() { + log("FAILED TO SHIP COVERAGE! but that's okay"); }); }); -execTask('SETUP', function () { +execTask('SETUP', function() { return Promise.try(function readVersion() { if (!ENV.ES_V) { if (ENV.ES_RELEASE) { @@ -141,8 +150,8 @@ execTask('SETUP', function () { } } - var match; - if (match = ENV.ES_V.match(/^(.*)_nightly$/)) { + var match = ENV.ES_V.match(/^(.*)_nightly$/); + if (match) { return [match[1], null]; } @@ -152,55 +161,56 @@ execTask('SETUP', function () { throw new Error('unable to parse ES_V ' + ENV.ES_V); }) - .then(function readOtherConf(ver) { - if (!ver) { - throw new Error('Unable to run the ci script without at least an ES_REF or ES_RELEASE environment var.'); - } + .then(function readOtherConf(ver) { + if (!ver) { + throw new Error( + 'Unable to run the ci script without at least an ES_REF or ES_RELEASE environment var.' + ); + } - log('ES_PORT:', ENV.ES_PORT = parseInt(ENV.ES_PORT || 9400, 10)); - log('ES_HOST:', ENV.ES_HOST = ENV.ES_HOST || 'localhost'); + log('ES_PORT:', (ENV.ES_PORT = parseInt(ENV.ES_PORT || 9400, 10))); + log('ES_HOST:', (ENV.ES_HOST = ENV.ES_HOST || 'localhost')); - if (ver[0]) log('ES_REF:', ENV.ES_REF = ver[0]); - else delete ENV.ES_REF; + if (ver[0]) log('ES_REF:', (ENV.ES_REF = ver[0])); + else delete ENV.ES_REF; - if (ver[1]) log('ES_RELEASE:', ENV.ES_RELEASE = ver[1]); - else delete ENV.ES_RELEASE; - }) - .then(function readTasks() { - if (!ENV.RUN) { - return _.filter(TASKS, { default: true }); - } - - return ENV.RUN - .split(',') - .map(function (name) { - return _.find(TASKS, { name: name.trim() }); + if (ver[1]) log('ES_RELEASE:', (ENV.ES_RELEASE = ver[1])); + else delete ENV.ES_RELEASE; }) - .filter(Boolean); - }); -}) -.then(function (queue) { - if (!queue.length) { - throw new Error('no tasks to run'); - } + .then(function readTasks() { + if (!ENV.RUN) { + return _.filter(TASKS, { default: true }); + } - // Recursively do tasks until the queue is empty - return (function next() { - if (!queue.length) return; - return execTask(queue.shift()).then(next); - }()); + return ENV.RUN.split(',') + .map(function(name) { + return _.find(TASKS, { name: name.trim() }); + }) + .filter(Boolean); + }); }) -.then(function () { - logImportant(chalk.bold.green('✔︎ SUCCESS')); -}) -.catch(function (e) { - logImportant(chalk.bold.red('✗ FAILURE\n\n' + e.stack)); + .then(function(queue) { + if (!queue.length) { + throw new Error('no tasks to run'); + } - // override process exit code once it is ready to close - process.once('exit', function () { - process.exit(1); + // Recursively do tasks until the queue is empty + return (function next() { + if (!queue.length) return; + return execTask(queue.shift()).then(next); + })(); + }) + .then(function() { + logImportant(chalk.bold.green('✔︎ SUCCESS')); + }) + .catch(function(e) { + logImportant(chalk.bold.red('✗ FAILURE\n\n' + e.stack)); + + // override process exit code once it is ready to close + process.once('exit', function() { + process.exit(1); + }); }); -}); /** **** * utils @@ -217,7 +227,7 @@ function logImportant(text) { } function push(m) { - return function () { + return function() { var args = _.toArray(arguments); var cb = args.pop(); this.push(m.apply(this, args)); @@ -227,8 +237,12 @@ function push(m) { function indent() { var str = through2( - push(function (chunk) { return String(chunk).replace(NL_RE, '$1 '); }), - push(function () { return '\n'; }) + push(function(chunk) { + return String(chunk).replace(NL_RE, '$1 '); + }), + push(function() { + return '\n'; + }) ); str.push(' '); return str; @@ -243,7 +257,7 @@ function task(name, def, fn) { TASKS.push({ name: name, default: def, - fn: fn + fn: fn, }); } @@ -254,20 +268,20 @@ function execTask(name, task) { } output = through2(); - output - .pipe(process.stdout, { end: false }); + output.pipe( + process.stdout, + { end: false } + ); log(chalk.white.underline(name)); taskOut = through2(); - taskOut - .pipe(indent()) - .pipe(output); + taskOut.pipe(indent()).pipe(output); function flushTaskOut() { - return new Promise(function (resolve) { + return new Promise(function(resolve) { // wait for the taskOut to finish writing before continuing - output.once('finish', function () { + output.once('finish', function() { log(''); resolve(); }); @@ -280,26 +294,33 @@ function execTask(name, task) { } function spawn(file, args, block) { - return new Promise(function (resolve, reject) { + return new Promise(function(resolve, reject) { var proc = cp.spawn(file, args, { cwd: ROOT, env: ENV, - stdio: [0, 'pipe', 'pipe'] + stdio: [0, 'pipe', 'pipe'], }); - proc.stdout.pipe(taskOut, { end: false }); - proc.stderr.pipe(taskOut, { end: false }); + proc.stdout.pipe( + taskOut, + { end: false } + ); + proc.stderr.pipe( + taskOut, + { end: false } + ); var stdout = ''; - proc.stdout - .pipe(through2(function (chunk, enc, cb) { - stdout += chunk; - cb(); - })); + proc.stdout.pipe( + through2(function(chunk, enc, cb) { + stdout += chunk; + cb(); + }) + ); if (block) block(proc); - proc.on('exit', function (code) { + proc.on('exit', function(code) { if (code > 0) { reject(new Error('non-zero exit code: ' + code)); } else { @@ -307,22 +328,25 @@ function spawn(file, args, block) { } }); - proc.on('error', function (origErr) { - reject(new Error('Unable to execute "' + file + ' ' + args.join(' ') + '": ' + origErr.message)); + proc.on('error', function(origErr) { + reject( + new Error( + 'Unable to execute "' + + file + + ' ' + + args.join(' ') + + '": ' + + origErr.message + ) + ); }); }); } function node(/* args... */) { - return spawn( - process.execPath, - _.toArray(arguments) - ); + return spawn(process.execPath, _.toArray(arguments)); } function grunt(/* args... */) { - return spawn( - GRUNT, - _.toArray(arguments) - ); + return spawn(GRUNT, _.toArray(arguments)); } diff --git a/scripts/eslint.js b/scripts/eslint.js new file mode 100644 index 000000000..a18319593 --- /dev/null +++ b/scripts/eslint.js @@ -0,0 +1,2 @@ +process.argv.push('.'); +require('eslint/bin/eslint'); diff --git a/scripts/generate/api_index.js b/scripts/generate/api_index.js index 8ac27b02d..0a338abb8 100644 --- a/scripts/generate/api_index.js +++ b/scripts/generate/api_index.js @@ -1,25 +1,40 @@ -module.exports = function (done) { +module.exports = function(done) { var _ = require('lodash'); var gruntUtils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial( + require('path').join, + require('find-root')(__dirname) + ); var write = require('fs').writeFileSync; var nodeApiIndex = fromRoot('src/lib/apis/index.js'); var browserApiIndex = fromRoot('src/lib/apis/browser_index.js'); - write(nodeApiIndex, require('./templates').apiIndex({ - branches: gruntUtils.branches - }), 'utf8'); + write( + nodeApiIndex, + require('./templates').apiIndex({ + branches: gruntUtils.branches, + }), + 'utf8' + ); console.log(chalk.white.bold('wrote'), 'api index to', nodeApiIndex); - write(browserApiIndex, require('./templates').apiIndexBrowser({ - branches: gruntUtils.browserBranches - }), 'utf8'); + write( + browserApiIndex, + require('./templates').apiIndexBrowser({ + branches: gruntUtils.browserBranches, + }), + 'utf8' + ); - console.log(chalk.white.bold('wrote'), 'browser api index to', browserApiIndex); + console.log( + chalk.white.bold('wrote'), + 'browser api index to', + browserApiIndex + ); done(); }; diff --git a/scripts/generate/configuration_docs.js b/scripts/generate/configuration_docs.js index 212ba9a2e..7309fffca 100644 --- a/scripts/generate/configuration_docs.js +++ b/scripts/generate/configuration_docs.js @@ -1,8 +1,11 @@ -module.exports = function (done) { +module.exports = function(done) { var _ = require('lodash'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial( + require('path').join, + require('find-root')(__dirname) + ); var write = require('fs').writeFile; var outputPath = fromRoot('docs/configuration.asciidoc'); diff --git a/scripts/generate/doc_index.js b/scripts/generate/doc_index.js index d359219bb..6eadded45 100644 --- a/scripts/generate/doc_index.js +++ b/scripts/generate/doc_index.js @@ -1,18 +1,26 @@ -module.exports = function (done) { +module.exports = function(done) { var _ = require('lodash'); var gruntUtils = require('../../grunt/utils'); var chalk = require('chalk'); - var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); + var fromRoot = _.partial( + require('path').join, + require('find-root')(__dirname) + ); var write = require('fs').writeFile; var outputPath = fromRoot('docs/index.asciidoc'); - write(outputPath, require('./templates').docsIndex({ - apiFiles: gruntUtils.stableBranches.map(function (branch) { - return 'api_methods' + gruntUtils.branchSuffix(branch) + '.asciidoc'; - }) - }), 'utf8', done); + write( + outputPath, + require('./templates').docsIndex({ + apiFiles: gruntUtils.stableBranches.map(function(branch) { + return 'api_methods' + gruntUtils.branchSuffix(branch) + '.asciidoc'; + }), + }), + 'utf8', + done + ); console.log(chalk.white.bold('wrote'), 'doc index to', outputPath); }; diff --git a/scripts/generate/index.js b/scripts/generate/index.js index d620816bb..f5a073305 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -2,30 +2,29 @@ var async = require('async'); var fs = require('fs'); var spawn = require('../_spawn'); -var argv = require('optimist') - .options({ - verbose: { - alias: 'v', - default: false, - boolean: true - }, - api: { - default: true, - boolean: true - }, - tests: { - default: true, - boolean: true - }, - update: { - default: true, - boolean: true - }, - branch: { - default: null, - string: true - } - }); +var argv = require('optimist').options({ + verbose: { + alias: 'v', + default: false, + boolean: true, + }, + api: { + default: true, + boolean: true, + }, + tests: { + default: true, + boolean: true, + }, + update: { + default: true, + boolean: true, + }, + branch: { + default: null, + string: true, + }, +}); var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); @@ -59,82 +58,101 @@ var paths = { docs: fromRoot('docs'), docsIndex: fromRoot('docs/index.asciidoc'), apiSrc: 'src/lib/apis', - getArchiveDir: function (branch) { + getArchiveDir: function(branch) { return fromRoot('src/_elasticsearch_' + utils.snakeCase(branch)); }, - getArchiveTarball: function (branch) { + getArchiveTarball: function(branch) { return fromRoot('src/_elasticsearch_' + utils.snakeCase(branch) + '.tar'); }, - getSpecPathInRepo: function (branch) { - return /^v?(master|[2-9]\.)/.test(branch) ? 'rest-api-spec/src/main/resources/rest-api-spec' : 'rest-api-spec'; - } + getSpecPathInRepo: function(branch) { + return /^v?(master|[2-9]\.)/.test(branch) + ? 'rest-api-spec/src/main/resources/rest-api-spec' + : 'rest-api-spec'; + }, }; function isDirectory(dir) { var stat; - try { stat = fs.statSync(dir); } catch (e) {} - return (stat && stat.isDirectory()); + try { + stat = fs.statSync(dir); + } catch (e) {} + return stat && stat.isDirectory(); } function dirFilter(dir, fn) { try { - return fs.readdirSync(dir) - .filter(function (name) { - return name !== '.' && name !== '..' && fn(name); - }) - .map(function (filename) { - return path.join(dir, filename); - }); + return fs + .readdirSync(dir) + .filter(function(name) { + return name !== '.' && name !== '..' && fn(name); + }) + .map(function(filename) { + return path.join(dir, filename); + }); } catch (e) { return []; } } function dirRegex(dir, regexp) { - return dirFilter(dir, function (name) { + return dirFilter(dir, function(name) { return name.match(regexp); }); } function dirOpts(dir, opts) { opts = _.isArray(opts) ? opts : [opts]; - return dirFilter(dir, function (name) { + return dirFilter(dir, function(name) { return _.includes(opts, name); }); } function spawnStep(cmd, args, cwd) { - return function (done) { - spawn(cmd, args, { - verbose: argv.verbose, - cwd: cwd - }, function (status) { - done(status ? new Error('Non-zero exit code: ' + status) : void 0); - }); + return function(done) { + spawn( + cmd, + args, + { + verbose: argv.verbose, + cwd: cwd, + }, + function(status) { + done(status ? new Error('Non-zero exit code: ' + status) : void 0); + } + ); }; } function initStep() { - return function (done) { + return function(done) { if (isDirectory(paths.esSrc)) { - async.series([ - spawnStep('git', ['remote', 'set-url', 'origin', esUrl], paths.esSrc) - ], done); + async.series( + [spawnStep('git', ['remote', 'set-url', 'origin', esUrl], paths.esSrc)], + done + ); } else { - async.series([ - spawnStep('git', ['init', '--bare', paths.esSrc], paths.root), - spawnStep('git', ['remote', 'add', 'origin', esUrl], paths.esSrc) - ], done); + async.series( + [ + spawnStep('git', ['init', '--bare', paths.esSrc], paths.root), + spawnStep('git', ['remote', 'add', 'origin', esUrl], paths.esSrc), + ], + done + ); } }; } function fetchBranchesStep() { - var branchArgs = branches.map(function (b) { return b + ':' + b; }); - return spawnStep('git', ['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs), paths.esSrc); + var 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$/; @@ -143,11 +161,11 @@ function findGeneratedApiFiles() { if (allBranches) { return [ dirRegex(paths.docs, anyApiMethodDocs), - dirRegex(paths.apiSrc, anyApiJsFiled) + dirRegex(paths.apiSrc, anyApiJsFiled), ]; } - return branches.reduce(function (files, branch) { + return branches.reduce(function(files, branch) { var b = utils.snakeCase(branch); files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc')); @@ -163,7 +181,6 @@ function findGeneratedApiFiles() { }, []); } - function clearGeneratedFiles() { var esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/; var generatedFiles = []; @@ -175,16 +192,16 @@ function clearGeneratedFiles() { generatedFiles.push(dirRegex(paths.src, esArchives)); var rmSteps = _.chain(generatedFiles) - .flattenDeep() - .uniq() - .map(function (path) { - return spawnStep('rm', ['-rf', path]); - }) - .value(); + .flattenDeep() + .uniq() + .map(function(path) { + return spawnStep('rm', ['-rf', path]); + }) + .value(); if (!rmSteps.length) return; - return function (done) { + return function(done) { return async.series(rmSteps, done); }; } @@ -199,7 +216,7 @@ function removePrevArchive(branch) { } function createArchive(branch) { - return function (done) { + return function(done) { var dir = paths.getArchiveDir(branch); var tarball = paths.getArchiveTarball(branch); var specPathInRepo = paths.getSpecPathInRepo(branch); @@ -210,36 +227,65 @@ function createArchive(branch) { return process.nextTick(done); } - async.series([ - spawnStep('mkdir', [dir], paths.root), - spawnStep('git', ['archive', '--format', 'tar', '--output', tarball, branch, specPathInRepo], paths.esSrc), - spawnStep('tar', ['-x', '-f', tarball, '-C', dir, '--strip-components', subDirCount]), - spawnStep('rm', [tarball]) - ], done); + async.series( + [ + spawnStep('mkdir', [dir], paths.root), + spawnStep( + 'git', + [ + 'archive', + '--format', + 'tar', + '--output', + tarball, + branch, + specPathInRepo, + ], + paths.esSrc + ), + spawnStep('tar', [ + '-x', + '-f', + tarball, + '-C', + dir, + '--strip-components', + subDirCount, + ]), + spawnStep('rm', [tarball]), + ], + done + ); }; } function generateStep(branch) { - return function (done) { - async.parallel([ - argv.api && async.apply(require('./js_api'), branch), - argv.tests && async.apply(require('./yaml_tests'), branch) - ].filter(Boolean), done); + return function(done) { + async.parallel( + [ + argv.api && async.apply(require('./js_api'), branch), + argv.tests && async.apply(require('./yaml_tests'), branch), + ].filter(Boolean), + done + ); }; } -var steps = [ - initStep(), - clearGeneratedFiles(), - fetchBranchesStep() -].filter(Boolean); +var steps = [initStep(), clearGeneratedFiles(), fetchBranchesStep()].filter( + Boolean +); -branches.forEach(function (branch) { - steps.push(_.partial(async.series, [ - removePrevArchive(branch), - createArchive(branch), - generateStep(branch) - ].filter(Boolean))); +branches.forEach(function(branch) { + steps.push( + _.partial( + async.series, + [ + removePrevArchive(branch), + createArchive(branch), + generateStep(branch), + ].filter(Boolean) + ) + ); }); if (argv.api) { @@ -251,15 +297,15 @@ if (argv.api) { } async.series( - steps.map(function (step) { - return function (done) { - step(function (err) { + steps.map(function(step) { + return function(done) { + step(function(err) { console.log('----\n'); done(err); }); }; }), - function (err) { + function(err) { if (err) { throw err; } diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index 8b6b424dc..20a6f63e0 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -1,4 +1,4 @@ -module.exports = function (branch, done) { +module.exports = function(branch, done) { /** * Read the API actions form the rest-api-spec repo. * @type {[type]} @@ -34,32 +34,29 @@ module.exports = function (branch, done) { var steps = [ readSpecFiles, - function (done) { + function(done) { parseSpecFiles(branch, done); }, - writeApiFile + writeApiFile, ]; if (!~gruntUtils.unstableBranches.indexOf(branch)) { - steps.push( - ensureDocsDir, - formatDocVars, - writeMethodDocs - ); + steps.push(ensureDocsDir, formatDocVars, writeMethodDocs); } // generate the API - async.series(steps, function (err) { + async.series(steps, function(err) { done(err); }); function readSpecFiles(done) { var apiDir = path.join(esDir, 'rest-api-spec/api/'); - files = fs.readdirSync(apiDir) - .filter(function (filename) { - return filename[0] !== '_' + files = fs + .readdirSync(apiDir) + .filter(function(filename) { + return filename[0] !== '_'; }) - .map(function (filename) { + .map(function(filename) { var module = require(apiDir + filename); delete require.cache[apiDir + filename]; return module; @@ -70,23 +67,25 @@ module.exports = function (branch, done) { function parseSpecFiles(branch, done) { var actions = []; - files.forEach(function (spec) { - __puke__transformSpec(branch, spec).forEach(function (action) { + files.forEach(function(spec) { + __puke__transformSpec(branch, spec).forEach(function(action) { actions.push(action); }); }); // collect the namespaces from the action locations - var namespaces = _.filter(_.map(actions, function (action) { - return action.location - .split('.') - .slice(0, -1) - .filter(step => step !== 'prototype') - .join('.prototype.') - })); + var namespaces = _.filter( + _.map(actions, function(action) { + return action.location + .split('.') + .slice(0, -1) + .filter(step => step !== 'prototype') + .join('.prototype.'); + }) + ); // seperate the proxy actions - var groups = _.groupBy(actions, function (action) { + var groups = _.groupBy(actions, function(action) { return action.proxy ? 'proxies' : 'normal'; }); @@ -94,7 +93,7 @@ module.exports = function (branch, done) { actions: groups.normal || [], proxies: groups.proxies || [], namespaces: _.uniq(namespaces.sort()), - clientActionModifier: overrides.clientActionModifier + clientActionModifier: overrides.clientActionModifier, }; if (!_.find(apiSpec.actions, { name: 'create' })) { @@ -105,7 +104,7 @@ module.exports = function (branch, done) { name: 'create', location: 'create', proxy: 'index', - transformBody: 'params.op_type = \'create\';' + transformBody: "params.op_type = 'create';", } ); @@ -116,36 +115,50 @@ module.exports = function (branch, done) { apiSpec.proxies.push(create); } - [].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'; + [].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'; try { - action.examples = fs.readFileSync(fromRoot('docs/_examples', examplePath), 'utf8'); + action.examples = fs.readFileSync( + fromRoot('docs/_examples', examplePath), + 'utf8' + ); } catch (e) { action.examples = '// no examples'; } try { - action.description = fs.readFileSync(fromRoot('docs/_descriptions', descriptionPath), 'utf8'); + action.description = fs.readFileSync( + fromRoot('docs/_descriptions', descriptionPath), + 'utf8' + ); } catch (e) { action.description = '// no description'; } - }) + }); done(); } function writeApiFile(done) { - var outputPath = fromRoot('src/lib/apis/' + utils.snakeCase(branch) + '.js'); + var outputPath = fromRoot( + 'src/lib/apis/' + utils.snakeCase(branch) + '.js' + ); fs.writeFileSync(outputPath, templates.apiFile(apiSpec)); - console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath); + console.log( + chalk.white.bold('wrote'), + apiSpec.actions.length, + 'api actions to', + outputPath + ); done(); } function ensureDocsDir(done) { - fs.stat(fromRoot('docs'), function (err, stat) { + fs.stat(fromRoot('docs'), function(err, stat) { if (err) { if (err.message.match(/enoent/i)) { fs.mkdir('../../docs', done); @@ -177,34 +190,37 @@ module.exports = function (branch, done) { function writeMethodDocs(done) { var filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc'); - fs.writeFile( - filename, - templates.apiMethods(docVars), - function (err) { - if (!err) { - console.log(chalk.white.bold('wrote'), branch + ' method docs to', filename); - } - done(err); + fs.writeFile(filename, templates.apiMethods(docVars), function(err) { + if (!err) { + console.log( + chalk.white.bold('wrote'), + branch + ' method docs to', + filename + ); } - ); + done(err); + }); } function __puke__transformSpec(branch, spec) { // eslint-disable-line var actions = []; // itterate all of the specs within the file, should only be one - _.each(spec, function (def, name) { + _.each(spec, function(def, name) { // camelcase the name name = _.map(name.split('.'), utils.camelCase).join('.'); if (name === 'cat.aliases') { - def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html'; + def.documentation = + 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html'; } - def.documentation = def.documentation ? def.documentation.replace( - /^https?:\/\/.+?\/guide\/en\/elasticsearch\/(.+?)\/.+?\//, - `https://www.elastic.co/guide/en/elasticsearch/$1/${branch}/` - ) : ''; + def.documentation = def.documentation + ? def.documentation.replace( + /^https?:\/\/.+?\/guide\/en\/elasticsearch\/(.+?)\/.+?\//, + `https://www.elastic.co/guide/en/elasticsearch/$1/${branch}/` + ) + : ''; var steps = name.split('.'); @@ -222,27 +238,36 @@ module.exports = function (branch, done) { var 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) { _.mergeWith(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 = { name: name, - methods: _.map(def.methods, function (m) { return m.toUpperCase(); }), + methods: _.map(def.methods, function(m) { + return m.toUpperCase(); + }), params: def.url.params, body: def.body || null, - path2lib: utils.repeat('../', steps.length + 1) + 'lib/' + path2lib: utils.repeat('../', steps.length + 1) + 'lib/', }; if (def.body && def.body.required) { @@ -255,63 +280,83 @@ module.exports = function (branch, done) { var urls = _.difference(def.url.paths, overrides.aliases[name]); var urlSignatures = []; - urls = _.map(urls, function (url) { + urls = _.map(urls, function(url) { var optionalVars = {}; var requiredVars = {}; var param; var name; var target; - var match; if (url.charAt(0) !== '/') { url = '/' + url; } - while (match = urlParamRE.exec(url)) { + while (true) { + const match = urlParamRE.exec(url); + if (!match) { + break; + } + name = utils.camelCase(match[1]); param = def.url.parts[name] || {}; - target = (param.required || !param.default) ? requiredVars : optionalVars; + target = + param.required || !param.default ? requiredVars : optionalVars; target[name] = _.omit(param, ['required', 'description', 'name']); } - urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':')); + urlSignatures.push( + _.union(_.keys(optionalVars), _.keys(requiredVars)) + .sort() + .join(':') + ); - return _.omitBy({ - fmt: url.replace(urlParamRE, function (full, match) { - return '<%=' + utils.camelCase(match) + '%>'; - }), - opt: _.size(optionalVars) ? optionalVars : null, - req: _.size(requiredVars) ? requiredVars : null, - sortOrder: _.size(requiredVars) * -1 - }, function (v) { - return !v; - }); + return _.omitBy( + { + fmt: url.replace(urlParamRE, function(full, match) { + return '<%=' + utils.camelCase(match) + '%>'; + }), + opt: _.size(optionalVars) ? optionalVars : null, + req: _.size(requiredVars) ? requiredVars : null, + sortOrder: _.size(requiredVars) * -1, + }, + function(v) { + return !v; + } + ); }); if (urlSignatures.length !== _.uniq(urlSignatures).length) { throw new Error( 'Multiple URLS with the same signature detected for ' + - spec.name + - '\n' + - _.map(urls, 'fmt').join('\n') + - '\n' + spec.name + + '\n' + + _.map(urls, 'fmt').join('\n') + + '\n' ); } if (urls.length > 1) { - spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function (url) { + spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function(url) { return _.omit(url, 'sortOrder'); }); } else { spec.url = _.omit(urls[0], 'sortOrder'); } - spec.params = _.transform(spec.params, function (note, param, name) { - // param.name = name; - note[name] = _.pick(param, [ - 'type', 'default', 'options', 'required', 'name' - ]); - }, {}); + spec.params = _.transform( + spec.params, + function(note, param, name) { + // param.name = name; + note[name] = _.pick(param, [ + 'type', + 'default', + 'options', + 'required', + 'name', + ]); + }, + {} + ); if (overrides.paramAsBody[name]) { spec.paramAsBody = overrides.paramAsBody[name]; @@ -322,8 +367,10 @@ module.exports = function (branch, done) { } // escape method names with "special" keywords - var location = spec.name.split('.').join('.prototype.') - .replace(/(^|\.)(delete|default)(\.|$)/g, '[\'$2\']'); + var location = spec.name + .split('.') + .join('.prototype.') + .replace(/(^|\.)(delete|default)(\.|$)/g, "['$2']"); var action = { _methods: spec.methods, @@ -334,13 +381,16 @@ module.exports = function (branch, done) { 'needBody', 'requestTimeout', 'bulkBody', - 'paramAsBody' + 'paramAsBody', ]), location: location, docUrl: def.documentation, name: spec.name, - namespace: spec.name.split('.').slice(0, -1).join('.'), - allParams: allParams + namespace: spec.name + .split('.') + .slice(0, -1) + .join('.'), + allParams: allParams, }; function hasMethod(/* ...methods */) { @@ -354,7 +404,10 @@ module.exports = function (branch, done) { return true; } function methodsAre(/* ...methods */) { - return hasMethod.apply(null, arguments) && arguments.length === action._methods.length; + return ( + hasMethod.apply(null, arguments) && + arguments.length === action._methods.length + ); } var method; @@ -365,17 +418,13 @@ module.exports = function (branch, done) { // we need to define what the default method(s) will be if (hasMethod('DELETE', 'POST')) { method = 'POST'; - } - else if (methodsAre('DELETE')) { + } else if (methodsAre('DELETE')) { method = 'DELETE'; - } - else if (methodsAre('POST', 'PUT')) { + } else if (methodsAre('POST', 'PUT')) { method = action.name.match(/put/i) ? 'PUT' : 'POST'; - } - else if (methodsAre('GET', 'POST')) { + } else if (methodsAre('GET', 'POST')) { method = 'POST'; - } - else if (methodsAre('GET', 'HEAD')) { + } else if (methodsAre('GET', 'HEAD')) { method = 'GET'; } } @@ -385,7 +434,9 @@ module.exports = function (branch, done) { action.spec.method = method; } } else { - throw new Error('unable to pick a method for ' + JSON.stringify(action, null, ' ')); + throw new Error( + 'unable to pick a method for ' + JSON.stringify(action, null, ' ') + ); } actions.push(action); diff --git a/scripts/generate/overrides.js b/scripts/generate/overrides.js index 4491d2792..16934dbb6 100644 --- a/scripts/generate/overrides.js +++ b/scripts/generate/overrides.js @@ -4,7 +4,7 @@ module.exports = [ paramAsBody: { scroll: 'scrollId', clearScroll: 'scrollId', - } + }, }, { version: '0.90.x', @@ -15,7 +15,7 @@ module.exports = [ '/_nodes/hot_threads', '/_cluster/nodes/{node_id}/hotthreads', '/_cluster/nodes/{node_id}/hot_threads', - '/_nodes/{node_id}/hot_threads' + '/_nodes/{node_id}/hot_threads', ], 'cluster.nodeInfo': [ '/_cluster/nodes', @@ -37,25 +37,19 @@ module.exports = [ '/_nodes/{node_id}/network', '/_nodes/{node_id}/transport', '/_nodes/{node_id}/http', - '/_nodes/{node_id}/plugin' - ], - 'cluster.nodeShutdown': [ - '/_cluster/nodes/_shutdown' + '/_nodes/{node_id}/plugin', ], + 'cluster.nodeShutdown': ['/_cluster/nodes/_shutdown'], 'cluster.nodeStats': [ '/_cluster/nodes/stats', '/_nodes/stats/{metric_family}', '/_nodes/stats/indices/{metric}/{fields}', '/_cluster/nodes/{node_id}/stats', '/_nodes/{node_id}/stats/{metric_family}', - '/_nodes/{node_id}/stats/indices/{metric}/{fields}' - ], - 'get': [ - '/{index}/{type}/{id}/_source' - ], - 'indices.deleteMapping': [ - '/{index}/{type}/_mapping' + '/_nodes/{node_id}/stats/indices/{metric}/{fields}', ], + get: ['/{index}/{type}/{id}/_source'], + 'indices.deleteMapping': ['/{index}/{type}/_mapping'], 'indices.stats': [ '_stats/{metric_family}', '/_stats/indexing', @@ -65,9 +59,9 @@ module.exports = [ '/{index}/_stats/{metric_family}', '/{index}/_stats/indexing', '/{index}/_stats/search/{search_groups}', - '/{index}/_stats/fielddata/{fields}' - ] - } + '/{index}/_stats/fielddata/{fields}', + ], + }, }, { version: '>=1.0.0', @@ -78,7 +72,7 @@ module.exports = [ '/_nodes/hot_threads', '/_cluster/nodes/{node_id}/hotthreads', '/_cluster/nodes/{node_id}/hot_threads', - '/_nodes/{node_id}/hot_threads' + '/_nodes/{node_id}/hot_threads', ], 'nodes.info': [ '/_cluster/nodes', @@ -100,27 +94,23 @@ module.exports = [ '/_nodes/{node_id}/network', '/_nodes/{node_id}/transport', '/_nodes/{node_id}/http', - '/_nodes/{node_id}/plugin' - ], - 'nodes.shutdown': [ - '/_cluster/nodes/_shutdown' + '/_nodes/{node_id}/plugin', ], + 'nodes.shutdown': ['/_cluster/nodes/_shutdown'], 'nodes.stats': [ '/_cluster/nodes/stats', '/_nodes/stats/{metric_family}', '/_nodes/stats/indices/{metric}/{fields}', '/_cluster/nodes/{node_id}/stats', '/_nodes/{node_id}/stats/{metric_family}', - '/_nodes/{node_id}/stats/indices/{metric}/{fields}' - ], - 'get': [ - '/{index}/{type}/{id}/_source' + '/_nodes/{node_id}/stats/indices/{metric}/{fields}', ], + get: ['/{index}/{type}/{id}/_source'], 'indices.deleteMapping': [ '/{index}/{type}', '/{index}/_mapping/{type}', '/{index}/{type}/_mappings', - '/{index}/_mappings/{type}' + '/{index}/_mappings/{type}', ], 'indices.putWarmer': [ // '/_warmer/{name}', @@ -128,23 +118,23 @@ module.exports = [ // '/{index}/{type}/_warmer/{name}', '/_warmers/{name}', '/{index}/_warmers/{name}', - '/{index}/{type}/_warmers/{name}' + '/{index}/{type}/_warmers/{name}', ], 'indices.deleteWarmer': [ // '/{index}/_warmer/{name}', '/{index}/_warmer', '/{index}/_warmers', - '/{index}/_warmers/{name}' + '/{index}/_warmers/{name}', ], 'indices.deleteAlias': [ // '/{index}/_alias/{name}', - '/{index}/_aliases/{name}' + '/{index}/_aliases/{name}', ], 'indices.putAlias': [ // '/{index}/_alias/{name}', // '/_alias/{name}', '/{index}/_aliases/{name}', - '/_aliases/{name}' + '/_aliases/{name}', ], 'indices.putMapping': [ // '/{index}/_mapping/{type}', @@ -154,7 +144,7 @@ module.exports = [ '/{index}/{type}/_mappings', '/{index}/_mappings/{type}', '/{index}/_mappings', - '/_mappings/{type}' + '/_mappings/{type}', ], 'indices.stats': [ '_stats/{metric_family}', @@ -165,31 +155,29 @@ module.exports = [ '/{index}/_stats/{metric_family}', '/{index}/_stats/indexing', '/{index}/_stats/search/{search_groups}', - '/{index}/_stats/fielddata/{fields}' - ] - } + '/{index}/_stats/fielddata/{fields}', + ], + }, }, { version: '>1.4.0', aliases: { 'indices.putAlias': [ // '/{index}/_alias/{name}', - '/{index}/_aliases/{name}' - ] - } + '/{index}/_aliases/{name}', + ], + }, }, { version: '<1.6.0', aliases: { - 'snapshot.create': [ - '/_snapshot/{repository}/{snapshot}' - ] - } + 'snapshot.create': ['/_snapshot/{repository}/{snapshot}'], + }, }, { version: '>=1.6.0', -// strange indentation makes pretty api files + // strange indentation makes pretty api files /* eslint-disable */ clientActionModifier: function (spec) { @@ -202,95 +190,92 @@ function (spec) { } }); } -/* eslint-enable */ - + /* eslint-enable */ }, { version: '>=2.0.0', aliases: { 'reindex.rethrottle': [ '/_update_by_query/{task_id}/_rethrottle', - '/_delete_by_query/{task_id}/_rethrottle' + '/_delete_by_query/{task_id}/_rethrottle', ], - 'reindexRethrottle': [ - '/_update_by_query/{task_id}/_rethrottle' - ] - } + reindexRethrottle: ['/_update_by_query/{task_id}/_rethrottle'], + }, }, { version: '>=5.0.0', mergeConcatParams: { bulk: { refresh: { - options: [''] - } + options: [''], + }, }, create: { refresh: { - options: [''] - } + options: [''], + }, }, index: { refresh: { - options: [''] - } + options: [''], + }, }, update: { refresh: { - options: [''] - } + options: [''], + }, }, delete: { refresh: { - options: [''] - } - } + options: [''], + }, + }, }, aliases: { - 'reindexRethrottle': [ + reindexRethrottle: [ '/_update_by_query/{task_id}/_rethrottle', - '/_delete_by_query/{task_id}/_rethrottle' - ] - } + '/_delete_by_query/{task_id}/_rethrottle', + ], + }, }, { version: '>=2.0', paramAsBody: { scroll: { param: 'scrollId', - body: 'scroll_id' + body: 'scroll_id', }, clearScroll: { param: 'scrollId', - body: 'scroll_id' - } - } + body: 'scroll_id', + }, + }, }, // description overrides by major version { version: '0.90.x', descriptions: { - search: 'search_1.x.asciidoc' - } + search: 'search_1.x.asciidoc', + }, }, { version: '1.x', descriptions: { - search: 'search_1.x.asciidoc' - } + search: 'search_1.x.asciidoc', + }, }, { version: '2.x', descriptions: { - search: 'search_2.x.asciidoc' - } + search: 'search_2.x.asciidoc', + }, }, // examples changed at 5.0 { version: '<5.0.0', examples: { - scroll: 'scroll_<5.0.asciidoc' - } + scroll: 'scroll_<5.0.asciidoc', + }, }, { version: '>=5.2 <5.5', @@ -299,7 +284,7 @@ function (spec) { param: 'scrollId', body: 'scroll_id', castToArray: true, - } - } - } + }, + }, + }, ]; diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index 2495abc35..e45eba38a 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,11 +1,9 @@ - var _ = require('lodash'); var utils = require('../../../src/lib/utils'); var gruntUtils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); - /** * we want strings in code to use single-quotes, so this will JSON encode vars, but then * modify them to follow our code standards. @@ -14,18 +12,20 @@ var path = require('path'); * @return {String} - our pretty string */ function stringify(thing, pretty) { - return (pretty ? JSON.stringify(thing, null, ' ') : JSON.stringify(thing)) - .replace(/'/g, '\\\'') - .replace(/\\?"/g, function (quote) { - // replace external (unescaped) double quotes with single quotes - return quote === '\\"' ? '"' : '\''; - }) - // inject a space between STRING array parts - .replace(/([^\\])','/g, '$1\', \'') - // remove quotes around key names that are only made up of letters - .replace(/^( +)'([a-zA-Z_]+)':/gm, '$1$2:') - // requote "special" key names - .replace(/^( +)(default):/gm, '$1\'$2\':'); + return ( + (pretty ? JSON.stringify(thing, null, ' ') : JSON.stringify(thing)) + .replace(/'/g, "\\'") + .replace(/\\?"/g, function(quote) { + // replace external (unescaped) double quotes with single quotes + return quote === '\\"' ? '"' : "'"; + }) + // inject a space between STRING array parts + .replace(/([^\\])','/g, "$1', '") + // remove quotes around key names that are only made up of letters + .replace(/^( +)'([a-zA-Z_]+)':/gm, '$1$2:') + // requote "special" key names + .replace(/^( +)(default):/gm, "$1'$2':") + ); } /** @@ -39,28 +39,30 @@ var templates = {}; * @type {Object} */ var templateGlobals = { - stringify: stringify, _: _, utils: utils, - indent: function (block, spaces) { + indent: function(block, spaces) { var indent = utils.repeat(' ', spaces); - return block.split('\n').map(function (line) { - return indent + line; - }).join('\n'); + return block + .split('\n') + .map(function(line) { + return indent + line; + }) + .join('\n'); }, - joinParagraphs: function (block) { + joinParagraphs: function(block) { return block.split('\n\n').join('\n+\n'); }, - paramType: function (type, paramName) { + paramType: function(type, paramName) { switch (type && type.toLowerCase ? type.toLowerCase() : 'any') { case 'time': case 'duration': - if (paramName === 'timestamp') return 'Timestamp' + if (paramName === 'timestamp') return 'Timestamp'; return '<>'; case 'any': return 'anything'; @@ -84,7 +86,7 @@ var templateGlobals = { } }, - paramWithDefault: function (name, def) { + paramWithDefault: function(name, def) { if (def) { return '[' + name + '=' + def + ']'; } else { @@ -94,16 +96,16 @@ var templateGlobals = { partials: templates, - gruntUtils: gruntUtils + gruntUtils: gruntUtils, }; -fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) { +fs.readdirSync(path.resolve(__dirname)).forEach(function(filename) { var name = filename.replace(/\..+$/, ''); if (name !== 'index') { templates[name] = _.template( fs.readFileSync(path.resolve(__dirname, filename), 'utf8'), { - imports: templateGlobals + imports: templateGlobals, } ); } diff --git a/scripts/generate/yaml_tests.js b/scripts/generate/yaml_tests.js index 247756feb..8528c6b17 100644 --- a/scripts/generate/yaml_tests.js +++ b/scripts/generate/yaml_tests.js @@ -1,4 +1,4 @@ -module.exports = function (branch, done) { +module.exports = function(branch, done) { /** * Creates a JSON version of the YAML test suite that can be simply bundled for use in the browser. */ @@ -14,24 +14,20 @@ module.exports = function (branch, done) { var esDir = fromRoot('src/_elasticsearch_' + utils.snakeCase(branch)); // generate the yaml tests - async.series([ - readYamlTests, - writeYamlTests, - writeTestIndex - ], done); + async.series([readYamlTests, writeYamlTests, writeTestIndex], done); function readYamlTests(done) { var testDir = path.join(esDir, 'rest-api-spec/test/'); function readDirectories(dir) { - fs.readdirSync(dir).forEach(function (filename) { + fs.readdirSync(dir).forEach(function(filename) { var filePath = path.join(dir, filename); var stat = fs.statSync(filePath); if (stat.isDirectory()) { readDirectories(filePath); } else if (filename.match(/\.yaml$/)) { - var file = tests[path.relative(testDir, filePath)] = []; - jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function (doc) { + var file = (tests[path.relative(testDir, filePath)] = []); + jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function(doc) { file.push(doc); }); } @@ -43,15 +39,21 @@ module.exports = function (branch, done) { } function writeYamlTests(done) { - var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + utils.snakeCase(branch) + '.json'); + var testFile = fromRoot( + 'test/integration/yaml_suite/yaml_tests_' + + utils.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_' + utils.snakeCase(branch) + '.js'); - fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8'); + var file = fromRoot( + 'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js' + ); + fs.writeFileSync(file, "require('./run')('" + branch + "');\n", 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML index to', file); done(); } diff --git a/scripts/release/bower.js b/scripts/release/bower.js index 3705c1dcb..89510e24d 100644 --- a/scripts/release/bower.js +++ b/scripts/release/bower.js @@ -16,30 +16,45 @@ bowerJson.version = esjsJson.version; bowerPackageJson.version = esjsJson.version; // write the new bower.json file -fs.writeFileSync(bowerDir + '/bower.json', JSON.stringify(bowerJson, null, ' ')); +fs.writeFileSync( + bowerDir + '/bower.json', + JSON.stringify(bowerJson, null, ' ') +); // write the new package.json file -fs.writeFileSync(bowerDir + '/package.json', JSON.stringify(bowerPackageJson, null, ' ')); +fs.writeFileSync( + bowerDir + '/package.json', + JSON.stringify(bowerPackageJson, null, ' ') +); function make(cmd, args) { return _.bind(spawn, null, cmd, args, { verbose: true, - cwd: bowerDir + cwd: bowerDir, }); } -async.series([ - make('git', ['add', '-A']), - make('git', ['commit', '-m', 'version ' + bowerJson.version]), - make('git', ['tag', '-a', 'v' + bowerJson.version, '-m', 'version ' + bowerJson.version]), - make('git', ['push', 'origin', 'master']), - make('git', ['push', '--tags', 'origin']), - make('npm', ['publish']) -], function (err) { - if (err) { - if (_.isNumber(err)) { - console.log('Non-zero exit code: %d', err); - } else { - console.log('Error: ', err.message ? err.message : err); +async.series( + [ + make('git', ['add', '-A']), + make('git', ['commit', '-m', 'version ' + bowerJson.version]), + make('git', [ + 'tag', + '-a', + 'v' + bowerJson.version, + '-m', + 'version ' + bowerJson.version, + ]), + make('git', ['push', 'origin', 'master']), + make('git', ['push', '--tags', 'origin']), + make('npm', ['publish']), + ], + function(err) { + if (err) { + if (_.isNumber(err)) { + console.log('Non-zero exit code: %d', err); + } else { + console.log('Error: ', err.message ? err.message : err); + } } } -}); +); diff --git a/src/elasticsearch.angular.js b/src/elasticsearch.angular.js index 514374714..6d0958ad7 100644 --- a/src/elasticsearch.angular.js +++ b/src/elasticsearch.angular.js @@ -10,14 +10,15 @@ var Client = require('./lib/client'); process.angular_build = true; /* global angular */ -angular.module('elasticsearch', []) - .factory('esFactory', ['$injector', '$q', function ($injector, $q) { - - var factory = function (config) { +angular.module('elasticsearch', []).factory('esFactory', [ + '$injector', + '$q', + function($injector, $q) { + var factory = function(config) { config = config || {}; config.connectionClass = AngularConnector; config.$injector = $injector; - config.defer = function () { + config.defer = function() { return $q.defer(); }; config.serializer = config.serializer || 'angular'; @@ -29,4 +30,5 @@ angular.module('elasticsearch', []) factory.Transport = require('./lib/transport'); return factory; - }]); + }, +]); diff --git a/src/elasticsearch.jquery.js b/src/elasticsearch.jquery.js index 740a2ee1f..c712b68fe 100644 --- a/src/elasticsearch.jquery.js +++ b/src/elasticsearch.jquery.js @@ -1,5 +1,5 @@ /* global jQuery */ -(function ($) { +(function($) { process.jquery_build = true; var es = require('./elasticsearch'); @@ -12,11 +12,10 @@ } $.es = $.extend({}, es); - $.es.Client = function (config) { + $.es.Client = function(config) { config = config || {}; config.defer = defer; config.$ = $; return new es.Client(config); }; - -}(jQuery)); +})(jQuery); diff --git a/src/elasticsearch.js b/src/elasticsearch.js index 4fc3e5116..9cb128c1d 100644 --- a/src/elasticsearch.js +++ b/src/elasticsearch.js @@ -2,9 +2,11 @@ // throw an error when they try to instanciate the exported function. // previous "elasticsearch" module -> https://github.com/ncb000gt/node-es function es() { - throw new Error('Looks like you are expecting the previous "elasticsearch" module. ' + - 'It is now the "es" module. To create a client with this module use ' + - '`new es.Client(params)`.'); + throw new Error( + 'Looks like you are expecting the previous "elasticsearch" module. ' + + 'It is now the "es" module. To create a client with this module use ' + + '`new es.Client(params)`.' + ); } es.Client = require('./lib/client'); diff --git a/src/lib/client.js b/src/lib/client.js index b3bbd7832..51e713be5 100755 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -35,8 +35,10 @@ function Client(config) { config = config || {}; if (config.__reused) { - throw new Error('Do not reuse objects to configure the elasticsearch Client class: ' + - 'https://github.com/elasticsearch/elasticsearch-js/issues/33'); + throw new Error( + 'Do not reuse objects to configure the elasticsearch Client class: ' + + 'https://github.com/elasticsearch/elasticsearch-js/issues/33' + ); } else { config.__reused = true; } @@ -51,23 +53,30 @@ function Client(config) { config.host = 'http://localhost:9200'; } - this.close = function () { + this.close = function() { this.transport.close(); }; this.transport = new Transport(config); - _.each(EsApiClient.prototype, _.bind(function (Fn, prop) { - if (Fn.prototype instanceof clientAction.ApiNamespace) { - this[prop] = new Fn(this.transport, this); - } - }, this)); + _.each( + EsApiClient.prototype, + _.bind(function(Fn, prop) { + if (Fn.prototype instanceof clientAction.ApiNamespace) { + this[prop] = new Fn(this.transport, this); + } + }, this) + ); delete this._namespaces; } - - EsApiClient.prototype = utils.funcEnum(config, 'apiVersion', Client.apis, '_default'); + EsApiClient.prototype = utils.funcEnum( + config, + 'apiVersion', + Client.apis, + '_default' + ); if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) { config.sniffEndpoint = '/_cluster/nodes'; } @@ -77,24 +86,25 @@ function Client(config) { if (config.plugins) { Constructor.prototype = _.cloneDeep(Constructor.prototype); - _.each(config.plugins, function (setup) { - Constructor = setup(Constructor, config, { - apis: require('./apis'), - connectors: require('./connectors'), - loggers: require('./loggers'), - selectors: require('./selectors'), - serializers: require('./serializers'), - Client: require('./client'), - clientAction: clientAction, - Connection: require('./connection'), - ConnectionPool: require('./connection_pool'), - Errors: require('./errors'), - Host: require('./host'), - Log: require('./log'), - Logger: require('./logger'), - NodesToHost: require('./nodes_to_host'), - Transport: require('./transport') - }) || Constructor; + _.each(config.plugins, function(setup) { + Constructor = + setup(Constructor, config, { + apis: require('./apis'), + connectors: require('./connectors'), + loggers: require('./loggers'), + selectors: require('./selectors'), + serializers: require('./serializers'), + Client: require('./client'), + clientAction: clientAction, + Connection: require('./connection'), + ConnectionPool: require('./connection_pool'), + Errors: require('./errors'), + Host: require('./host'), + Log: require('./log'), + Logger: require('./logger'), + NodesToHost: require('./nodes_to_host'), + Transport: require('./transport'), + }) || Constructor; }); } diff --git a/src/lib/client_action.js b/src/lib/client_action.js index aeb8444a6..03867fed3 100644 --- a/src/lib/client_action.js +++ b/src/lib/client_action.js @@ -1,4 +1,3 @@ - var _ = require('lodash'); var utils = require('./utils'); @@ -23,8 +22,8 @@ exports.proxyFactory = exports.factory.proxy; // export so that we can test this exports._resolveUrl = resolveUrl; -exports.ApiNamespace = function () {}; -exports.namespaceFactory = function () { +exports.ApiNamespace = function() {}; +exports.namespaceFactory = function() { function ClientNamespace(transport, client) { this.transport = transport; this.client = client; @@ -38,7 +37,7 @@ exports.namespaceFactory = function () { function makeFactoryWithModifier(modifier) { modifier = modifier || _.identity; - var factory = function (spec) { + var factory = function(spec) { spec = modifier(spec); if (!_.isPlainObject(spec.params)) { @@ -76,8 +75,8 @@ function makeFactoryWithModifier(modifier) { return action; }; - factory.proxy = function (fn, spec) { - return function (params, cb) { + factory.proxy = function(fn, spec) { + return function(params, cb) { if (typeof params === 'function') { cb = params; params = {}; @@ -98,15 +97,17 @@ function makeFactoryWithModifier(modifier) { } var castType = { - 'enum': function validSelection(param, val, name) { + enum: function validSelection(param, val, name) { if (_.isString(val) && val.indexOf(',') > -1) { val = commaSepList(val); } if (_.isArray(val)) { - return val.map(function (v) { - return validSelection(param, v, name); - }).join(','); + return val + .map(function(v) { + return validSelection(param, v, name); + }) + .join(','); } for (var i = 0; i < param.options.length; i++) { @@ -114,23 +115,28 @@ var castType = { return param.options[i]; } } - throw new TypeError('Invalid ' + name + ': expected ' + ( - param.options.length > 1 - ? 'one of ' + param.options.join(',') - : param.options[0] - )); + throw new TypeError( + 'Invalid ' + + name + + ': expected ' + + (param.options.length > 1 + ? 'one of ' + param.options.join(',') + : param.options[0]) + ); }, - duration: function (param, val, name) { + duration: function(param, val, name) { if (utils.isNumeric(val) || utils.isInterval(val)) { return val; } else { throw new TypeError( - 'Invalid ' + name + ': expected a number or interval ' + - '(an integer followed by one of M, w, d, h, m, s, y or ms).' + 'Invalid ' + + name + + ': expected a number or interval ' + + '(an integer followed by one of M, w, d, h, m, s, y or ms).' ); } }, - list: function (param, val, name) { + list: function(param, val, name) { switch (typeof val) { case 'number': case 'boolean': @@ -144,21 +150,25 @@ var castType = { } /* falls through */ default: - throw new TypeError('Invalid ' + name + ': expected be a comma separated list, array, number or string.'); + throw new TypeError( + 'Invalid ' + + name + + ': expected be a comma separated list, array, number or string.' + ); } }, - 'boolean': function (param, val) { + boolean: function(param, val) { val = _.isString(val) ? val.toLowerCase() : val; - return (val === 'no' || val === 'off') ? false : !!val; + return val === 'no' || val === 'off' ? false : !!val; }, - number: function (param, val, name) { + number: function(param, val, name) { if (utils.isNumeric(val)) { return val * 1; } else { throw new TypeError('Invalid ' + name + ': expected a number.'); } }, - string: function (param, val, name) { + string: function(param, val, name) { switch (typeof val) { case 'number': case 'string': @@ -167,24 +177,23 @@ var castType = { throw new TypeError('Invalid ' + name + ': expected a string.'); } }, - time: function (param, val, name) { + time: function(param, val, name) { if (typeof val === 'string') { return val; - } - else if (utils.isNumeric(val)) { + } else if (utils.isNumeric(val)) { return '' + val; - } - else if (val instanceof Date) { + } else if (val instanceof Date) { return '' + val.getTime(); - } - else { + } else { throw new TypeError('Invalid ' + name + ': expected some sort of time.'); } - } + }, }; function resolveUrl(url, params) { - var vars = {}, i, key; + var vars = {}; + var i; + var key; if (url.req) { // url has required params @@ -193,7 +202,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 @@ -201,7 +210,11 @@ function resolveUrl(url, params) { } else { // cast of copy required param if (castType[url.req[key].type]) { - vars[key] = castType[url.req[key].type](url.req[key], params[key], key); + vars[key] = castType[url.req[key].type]( + url.req[key], + params[key], + key + ); } else { vars[key] = params[key]; } @@ -215,11 +228,15 @@ 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) { - vars[key] = castType[url.opt[key].type](url.opt[key], params[key], key); + vars[key] = castType[url.opt[key].type]( + url.opt[key], + params[key], + key + ); } else { vars[key] = params[key]; } @@ -234,18 +251,23 @@ function resolveUrl(url, params) { url.template = _.template(url.fmt); } - return url.template(_.transform(vars, function (note, val, name) { - // encode each value - note[name] = encodeURIComponent(val); - // remove it from the params so that it isn't sent to the final request - delete params[name]; - }, {})); + return url.template( + _.transform( + vars, + function(note, val, name) { + // encode each value + note[name] = encodeURIComponent(val); + // remove it from the params so that it isn't sent to the final request + delete params[name]; + }, + {} + ) + ); } - function exec(transport, spec, params, cb) { var request = { - method: spec.method + method: spec.method, }; var query = {}; var i; @@ -259,7 +281,9 @@ function exec(transport, spec, params, cb) { if (typeof spec.paramAsBody === 'object') { params.body = {}; if (spec.paramAsBody.castToArray) { - params.body[spec.paramAsBody.body] = [].concat(params[spec.paramAsBody.param]); + params.body[spec.paramAsBody.body] = [].concat( + params[spec.paramAsBody.param] + ); } else { params.body[spec.paramAsBody.body] = params[spec.paramAsBody.param]; } @@ -290,7 +314,8 @@ function exec(transport, spec, params, cb) { request.path = resolveUrl(spec.url, params); } else { for (i = 0; i < spec.urls.length; i++) { - if (request.path = resolveUrl(spec.urls[i], params)) { + request.path = resolveUrl(spec.urls[i], params); + if (request.path) { break; } } @@ -299,18 +324,25 @@ 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]; - throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', ')); + throw new TypeError( + 'Unable to build a path with those params. Supply at least ' + + _.keys(minUrl.req).join(', ') + ); } // build the query string if (!spec.paramKeys) { // build a key list on demand spec.paramKeys = _.keys(spec.params); - spec.requireParamKeys = _.transform(spec.params, function (req, param, key) { - if (param.required) { - req.push(key); - } - }, []); + spec.requireParamKeys = _.transform( + spec.params, + function(req, param, key) { + if (param.required) { + req.push(key); + } + }, + [] + ); } for (var key in params) { @@ -331,16 +363,23 @@ function exec(transport, spec, params, cb) { default: var paramSpec = spec.params[key]; if (paramSpec) { - // param keys don't always match the param name, in those cases it's stored in the param def as "name" + // param keys don't always match the param name, in those cases it's stored in the param def as "name" paramSpec.name = paramSpec.name || key; if (params[key] != null) { if (castType[paramSpec.type]) { - query[paramSpec.name] = castType[paramSpec.type](paramSpec, params[key], key); + query[paramSpec.name] = castType[paramSpec.type]( + paramSpec, + params[key], + key + ); } else { 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]; } } @@ -351,9 +390,11 @@ 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]); + throw new TypeError( + 'Missing required parameter ' + spec.requireParamKeys[i] + ); } } @@ -363,7 +404,7 @@ function exec(transport, spec, params, cb) { } function commaSepList(str) { - return str.split(',').map(function (i) { + return str.split(',').map(function(i) { return i.trim(); }); } diff --git a/src/lib/connection.js b/src/lib/connection.js index 200108614..7221a7c45 100644 --- a/src/lib/connection.js +++ b/src/lib/connection.js @@ -41,11 +41,11 @@ utils.inherits(ConnectionAbstract, EventEmitter); * @param params.requestTimeout {Integer} - The amount of time in milliseconds that this request should be allowed to run for. * @param cb {Function} - A callback to be called once with `cb(err, responseBody, responseStatus)` */ -ConnectionAbstract.prototype.request = function () { +ConnectionAbstract.prototype.request = function() { throw new Error('Connection#request must be overwritten by the Connector'); }; -ConnectionAbstract.prototype.ping = function (params, cb) { +ConnectionAbstract.prototype.ping = function(params, cb) { if (typeof params === 'function') { cb = params; params = null; @@ -62,33 +62,40 @@ ConnectionAbstract.prototype.ping = function (params, cb) { requestTimeout = params.requestTimeout; } - abort = this.request(_.defaults(params || {}, { - path: '/', - method: 'HEAD' - }), function (err) { - if (aborted) { - return; + abort = this.request( + _.defaults(params || {}, { + path: '/', + method: 'HEAD', + }), + function(err) { + if (aborted) { + return; + } + clearTimeout(requestTimeoutId); + if (cb) { + cb(err); + } } - clearTimeout(requestTimeoutId); - if (cb) { - cb(err); - } - }); + ); if (requestTimeout) { - requestTimeoutId = setTimeout(function () { + requestTimeoutId = setTimeout(function() { if (abort) { abort(); } aborted = true; if (cb) { - cb(new errors.RequestTimeout('Ping Timeout after ' + requestTimeout + 'ms')); + cb( + new errors.RequestTimeout( + 'Ping Timeout after ' + requestTimeout + 'ms' + ) + ); } }, requestTimeout); } }; -ConnectionAbstract.prototype.setStatus = function (status) { +ConnectionAbstract.prototype.setStatus = function(status) { var origStatus = this.status; this.status = status; diff --git a/src/lib/connection_pool.js b/src/lib/connection_pool.js index 982d7c2d7..14039b2b5 100644 --- a/src/lib/connection_pool.js +++ b/src/lib/connection_pool.js @@ -28,23 +28,41 @@ function ConnectionPool(config) { this._config = config; // get the selector config var - this.selector = utils.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); + this.selector = utils.funcEnum( + config, + 'selector', + ConnectionPool.selectors, + ConnectionPool.defaultSelector + ); // get the connection class - this.Connection = utils.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, - ConnectionPool.defaultConnectionClass); + this.Connection = utils.funcEnum( + config, + 'connectionClass', + ConnectionPool.connectionClasses, + ConnectionPool.defaultConnectionClass + ); // time that connections will wait before being revived - this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000; - this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5; - this.calcDeadTimeout = utils.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); + this.deadTimeout = config.hasOwnProperty('deadTimeout') + ? config.deadTimeout + : 60000; + this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') + ? config.maxDeadTimeout + : 18e5; + this.calcDeadTimeout = utils.funcEnum( + config, + 'calcDeadTimeout', + ConnectionPool.calcDeadTimeoutOptions, + 'exponential' + ); // a map of connections to their "id" property, used when sniffing this.index = {}; this._conns = { alive: [], - dead: [] + dead: [], }; // information about timeouts for dead connections @@ -57,17 +75,21 @@ ConnectionPool.defaultSelector = 'roundRobin'; // get the connection options ConnectionPool.connectionClasses = require('./connectors'); -ConnectionPool.defaultConnectionClass = ConnectionPool.connectionClasses._default; +ConnectionPool.defaultConnectionClass = + ConnectionPool.connectionClasses._default; delete ConnectionPool.connectionClasses._default; // the function that calculates timeouts based on attempts ConnectionPool.calcDeadTimeoutOptions = { - flat: function (attempt, baseTimeout) { + flat: function(attempt, baseTimeout) { return baseTimeout; }, - exponential: function (attempt, baseTimeout) { - return Math.min(baseTimeout * 2 * Math.pow(2, (attempt * 0.5 - 1)), this.maxDeadTimeout); - } + exponential: function(attempt, baseTimeout) { + return Math.min( + baseTimeout * 2 * Math.pow(2, attempt * 0.5 - 1), + this.maxDeadTimeout + ); + }, }; /** @@ -81,7 +103,7 @@ ConnectionPool.calcDeadTimeoutOptions = { * @param {Function} cb [description] * @return {[type]} [description] */ -ConnectionPool.prototype.select = function (cb) { +ConnectionPool.prototype.select = function(cb) { if (this._conns.alive.length) { if (this.selector.length > 1) { this.selector(this._conns.alive, cb); @@ -107,13 +129,17 @@ ConnectionPool.prototype.select = function (cb) { * @param {String} oldStatus - the connection's old status * @param {ConnectionAbstract} connection - the connection object itself */ -ConnectionPool.prototype.onStatusSet = utils.handler(function (status, oldStatus, connection) { +ConnectionPool.prototype.onStatusSet = utils.handler(function( + status, + oldStatus, + connection +) { var index; - var died = (status === 'dead'); - var wasAlreadyDead = (died && oldStatus === 'dead'); - var revived = (!died && oldStatus === 'dead'); - var noChange = (oldStatus === status); + 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]; @@ -150,7 +176,7 @@ ConnectionPool.prototype.onStatusSet = utils.handler(function (status, oldStatus * Handler used to clear the times created when a connection dies * @param {ConnectionAbstract} connection */ -ConnectionPool.prototype._onConnectionRevived = function (connection) { +ConnectionPool.prototype._onConnectionRevived = function(connection) { var timeout; for (var i = 0; i < this._timeouts.length; i++) { if (this._timeouts[i].conn === connection) { @@ -169,7 +195,10 @@ ConnectionPool.prototype._onConnectionRevived = function (connection) { * @param {ConnectionAbstract} connection * @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true */ -ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) { +ConnectionPool.prototype._onConnectionDied = function( + connection, + alreadyWasDead +) { var timeout; if (alreadyWasDead) { for (var i = 0; i < this._timeouts.length; i++) { @@ -182,15 +211,15 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea timeout = { conn: connection, attempt: 0, - revive: function (cb) { + revive: function(cb) { timeout.attempt++; - connection.ping(function (err) { + connection.ping(function(err) { connection.setStatus(err ? 'dead' : 'alive'); if (cb && typeof cb === 'function') { cb(err); } }); - } + }, }; this._timeouts.push(timeout); } @@ -204,7 +233,7 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea timeout.runAt = utils.now() + ms; }; -ConnectionPool.prototype._selectDeadConnection = function (cb) { +ConnectionPool.prototype._selectDeadConnection = function(cb) { var orderedTimeouts = _.sortBy(this._timeouts, 'runAt'); var log = this.log; @@ -221,7 +250,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) { } if (timeout.conn.status === 'dead') { - timeout.revive(function (err) { + timeout.revive(function(err) { if (err) { log.warning('Unable to revive connection: ' + timeout.conn.id); process.nextTick(next); @@ -247,7 +276,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) { * @param {string} [status] - optional status of the connection to fetch * @param {Number} [limit] - optional limit on the number of connections to return */ -ConnectionPool.prototype.getConnections = function (status, limit) { +ConnectionPool.prototype.getConnections = function(status, limit) { var list; if (status) { list = this._conns[status]; @@ -268,7 +297,7 @@ ConnectionPool.prototype.getConnections = function (status, limit) { * * @param {ConnectionAbstract} connection - The connection to add */ -ConnectionPool.prototype.addConnection = function (connection) { +ConnectionPool.prototype.addConnection = function(connection) { if (!connection.id) { connection.id = connection.host.toString(); } @@ -286,7 +315,7 @@ ConnectionPool.prototype.addConnection = function (connection) { * * @param {ConnectionAbstract} connection - The connection to remove/close */ -ConnectionPool.prototype.removeConnection = function (connection) { +ConnectionPool.prototype.removeConnection = function(connection) { if (!connection.id) { connection.id = connection.host.toString(); } @@ -304,7 +333,7 @@ ConnectionPool.prototype.removeConnection = function (connection) { * * @param {Host[]} hosts - An array of Host instances. */ -ConnectionPool.prototype.setHosts = function (hosts) { +ConnectionPool.prototype.setHosts = function(hosts) { var connection; var i; var id; @@ -329,8 +358,8 @@ ConnectionPool.prototype.setHosts = function (hosts) { } }; -ConnectionPool.prototype.getAllHosts = function () { - return _.values(this.index).map(function (connection) { +ConnectionPool.prototype.getAllHosts = function() { + return _.values(this.index).map(function(connection) { return connection.host; }); }; @@ -338,7 +367,7 @@ ConnectionPool.prototype.getAllHosts = function () { /** * Close the conncetion pool, as well as all of it's connections */ -ConnectionPool.prototype.close = function () { +ConnectionPool.prototype.close = function() { this.setHosts([]); }; ConnectionPool.prototype.empty = ConnectionPool.prototype.close; diff --git a/src/lib/connectors/angular.js b/src/lib/connectors/angular.js index 836d4d1b7..c8e9f7c24 100644 --- a/src/lib/connectors/angular.js +++ b/src/lib/connectors/angular.js @@ -14,15 +14,18 @@ function AngularConnector(host, config) { ConnectionAbstract.call(this, host, config); var self = this; - config.$injector.invoke(['$http', '$q', function ($http, $q) { - self.$q = $q; - self.$http = $http; - }]); - + config.$injector.invoke([ + '$http', + '$q', + function($http, $q) { + self.$q = $q; + self.$http = $http; + }, + ]); } utils.inherits(AngularConnector, ConnectionAbstract); -AngularConnector.prototype.request = function (params, cb) { +AngularConnector.prototype.request = function(params, cb) { var abort = this.$q.defer(); this.$http({ @@ -34,18 +37,21 @@ AngularConnector.prototype.request = function (params, cb) { transformRequest: [], transformResponse: [], // not actually for timing out, that's handled by the transport - timeout: abort.promise - }).then(function (response) { - cb(null, response.data, response.status, response.headers()); - }, function (err) { - if (err.status) { - cb(null, err.data, err.status, err.headers()); - } else { - cb(new ConnectionFault(err.message)); + timeout: abort.promise, + }).then( + function(response) { + cb(null, response.data, response.status, response.headers()); + }, + function(err) { + if (err.status) { + cb(null, err.data, err.status, err.headers()); + } else { + cb(new ConnectionFault(err.message)); + } } - }); + ); - return function () { + return function() { abort.resolve(); }; }; diff --git a/src/lib/connectors/browser_index.js b/src/lib/connectors/browser_index.js index dfe9abbbc..41dcbacda 100644 --- a/src/lib/connectors/browser_index.js +++ b/src/lib/connectors/browser_index.js @@ -1,12 +1,12 @@ var opts = { xhr: require('./xhr'), jquery: require('./jquery'), - angular: require('./angular') + angular: require('./angular'), }; var _ = require('lodash'); // remove modules that have been ignored by browserify -_.each(opts, function (conn, name) { +_.each(opts, function(conn, name) { if (typeof conn !== 'function') { delete opts[name]; } diff --git a/src/lib/connectors/http.js b/src/lib/connectors/http.js index 19d7eb03f..1208689a4 100644 --- a/src/lib/connectors/http.js +++ b/src/lib/connectors/http.js @@ -10,7 +10,7 @@ module.exports = HttpConnector; var handles = { http: require('http'), - https: require('https') + https: require('https'), }; var _ = require('lodash'); var utils = require('../utils'); @@ -19,7 +19,7 @@ var qs = require('querystring'); var AgentKeepAlive = require('agentkeepalive'); var ConnectionAbstract = require('../connection'); var zlib = require('zlib'); -var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/ +var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; /** * Connector used to talk to an elasticsearch node via HTTP @@ -33,8 +33,12 @@ function HttpConnector(host, config) { this.hand = handles[this.host.protocol]; if (!this.hand) { - throw new TypeError('Invalid protocol "' + this.host.protocol + - '", expected one of ' + _.keys(handles).join(', ')); + throw new TypeError( + 'Invalid protocol "' + + this.host.protocol + + '", expected one of ' + + _.keys(handles).join(', ') + ); } this.useSsl = this.host.protocol === 'https'; @@ -44,19 +48,21 @@ function HttpConnector(host, config) { keepAlive: true, keepAliveInterval: 1000, keepAliveMaxFreeSockets: 256, - keepAliveFreeSocketTimeout: 60000 + keepAliveFreeSocketTimeout: 60000, }); - this.agent = config.createNodeAgent ? config.createNodeAgent(this, config) : this.createAgent(config); + this.agent = config.createNodeAgent + ? config.createNodeAgent(this, config) + : this.createAgent(config); } utils.inherits(HttpConnector, ConnectionAbstract); -HttpConnector.prototype.onStatusSet = utils.handler(function (status) { +HttpConnector.prototype.onStatusSet = utils.handler(function(status) { if (status === 'closed') { var agent = this.agent; var toRemove = []; - var collectSockets = function (sockets, host) { - _.each(sockets, function (s) { + var collectSockets = function(sockets, host) { + _.each(sockets, function(s) { if (s) toRemove.push([host, s]); }); }; @@ -66,15 +72,16 @@ HttpConnector.prototype.onStatusSet = utils.handler(function (status) { _.each(agent.sockets, collectSockets); _.each(agent.freeSockets, collectSockets); - _.each(toRemove, function (args) { - var host = args[0], socket = args[1]; + _.each(toRemove, function(args) { + var host = args[0]; + var socket = args[1]; agent.removeSocket(socket, parseUrl(host)); socket.destroy(); }); } }); -HttpConnector.prototype.createAgent = function (config) { +HttpConnector.prototype.createAgent = function(config) { var Agent = this.hand.Agent; // the class if (config.forever) { @@ -89,7 +96,7 @@ HttpConnector.prototype.createAgent = function (config) { return new Agent(this.makeAgentConfig(config)); }; -HttpConnector.prototype.makeAgentConfig = function (config) { +HttpConnector.prototype.makeAgentConfig = function(config) { var agentConfig = { keepAlive: config.keepAlive, keepAliveMsecs: config.keepAliveInterval, @@ -105,7 +112,7 @@ HttpConnector.prototype.makeAgentConfig = function (config) { return agentConfig; }; -HttpConnector.prototype.makeReqParams = function (params) { +HttpConnector.prototype.makeReqParams = function(params) { params = params || {}; var host = this.host; @@ -116,7 +123,7 @@ HttpConnector.prototype.makeReqParams = function (params) { port: host.port, path: (host.path || '') + (params.path || ''), headers: host.getHeaders(params.headers), - agent: this.agent + agent: this.agent, }; if (!reqParams.path) { @@ -131,7 +138,7 @@ HttpConnector.prototype.makeReqParams = function (params) { return reqParams; }; -HttpConnector.prototype.request = function (params, cb) { +HttpConnector.prototype.request = function(params, cb) { var incoming; var timeoutId; var request; @@ -144,7 +151,7 @@ HttpConnector.prototype.request = function (params, cb) { // general clean-up procedure to run after the request // completes, has an error, or is aborted. - var cleanUp = _.bind(function (err) { + var cleanUp = _.bind(function(err) { clearTimeout(timeoutId); if (request) { @@ -155,7 +162,7 @@ HttpConnector.prototype.request = function (params, cb) { incoming.removeAllListeners(); } - if ((err instanceof Error) === false) { + if (err instanceof Error === false) { err = void 0; } @@ -168,11 +175,11 @@ HttpConnector.prototype.request = function (params, cb) { }, this); if (INVALID_PATH_REGEX.test(reqParams.path) === true) { - cb(new TypeError('ERR_UNESCAPED_CHARACTERS: ' + reqParams.path)) - return function () {} + cb(new TypeError('ERR_UNESCAPED_CHARACTERS: ' + reqParams.path)); + return function() {}; } - request = this.hand.request(reqParams, function (_incoming) { + request = this.hand.request(reqParams, function(_incoming) { incoming = _incoming; status = incoming.statusCode; headers = incoming.headers; @@ -184,7 +191,7 @@ HttpConnector.prototype.request = function (params, cb) { } incoming.setEncoding('utf8'); - incoming.on('data', function (d) { + incoming.on('data', function(d) { response += d; }); @@ -205,7 +212,7 @@ HttpConnector.prototype.request = function (params, cb) { request.end(); } - return function () { + return function() { request.abort(); }; }; diff --git a/src/lib/connectors/index.js b/src/lib/connectors/index.js index e35375cae..e4156ce34 100644 --- a/src/lib/connectors/index.js +++ b/src/lib/connectors/index.js @@ -1,4 +1,4 @@ module.exports = { http: require('./http'), - _default: 'http' + _default: 'http', }; diff --git a/src/lib/connectors/jquery.js b/src/lib/connectors/jquery.js index e128080ba..9e5208856 100644 --- a/src/lib/connectors/jquery.js +++ b/src/lib/connectors/jquery.js @@ -16,34 +16,35 @@ function JqueryConnector(host, config) { } utils.inherits(JqueryConnector, ConnectionAbstract); -JqueryConnector.prototype.request = function (params, cb) { +JqueryConnector.prototype.request = function(params, cb) { var ajax = { url: this.host.makeUrl(params), data: params.body, type: params.method, dataType: 'text', headers: this.host.getHeaders(params.headers), - done: cb + done: cb, }; - var jqXHR = jQuery.ajax(ajax) - .done(function (data) { + var jqXHR = jQuery + .ajax(ajax) + .done(function(data) { cb(null, data, jqXHR.statusCode(), { - 'content-type': jqXHR.getResponseHeader('content-type') + 'content-type': jqXHR.getResponseHeader('content-type'), }); }) - .fail(function (a, b, err) { + .fail(function(a, b, err) { // if response is available, execute cb. Else throw ConnectionFault if (a && a.responseText) { cb(null, a.responseText, jqXHR.statusCode(), { - 'content-type': jqXHR.getResponseHeader('content-type') + 'content-type': jqXHR.getResponseHeader('content-type'), }); } else { cb(new ConnectionFault(err && err.message)); } }); - return function () { + return function() { jqXHR.abort(); }; }; diff --git a/src/lib/connectors/xhr.js b/src/lib/connectors/xhr.js index 72647ba18..1edf1abf4 100644 --- a/src/lib/connectors/xhr.js +++ b/src/lib/connectors/xhr.js @@ -5,8 +5,9 @@ */ module.exports = XhrConnector; -/* jshint browser:true */ +/* eslint-env browser */ +var _ = require('lodash'); var utils = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; @@ -25,32 +26,31 @@ var getXhr = _.noop; if (typeof XMLHttpRequest !== 'undefined') { // rewrite the getXhr method to always return the native implementation - getXhr = function () { + getXhr = function() { return new XMLHttpRequest(); }; } else { // find the first MS implementation available getXhr = _(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']) - .map(function (appName) { - /* jshint unused: false */ - try { - var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars - return function () { - return new window.ActiveXObject(appName); - }; - } catch (e) { - return false; - } - }) - .compact() - .head(); + .map(function(appName) { + try { + var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars + return function() { + return new window.ActiveXObject(appName); + }; + } catch (e) { + return false; + } + }) + .compact() + .head(); } if (!getXhr) { throw new Error('getXhr(): XMLHttpRequest not available'); } -XhrConnector.prototype.request = function (params, cb) { +XhrConnector.prototype.request = function(params, cb) { var xhr = getXhr(); var timeoutId; var host = this.host; @@ -70,18 +70,20 @@ XhrConnector.prototype.request = function (params, cb) { } } - xhr.onreadystatechange = function () { + xhr.onreadystatechange = function() { 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.'); + var err = xhr.status + ? void 0 + : new ConnectionFault(xhr.statusText || 'Request failed to complete.'); cb(err, xhr.responseText, xhr.status); } }; xhr.send(params.body || void 0); - return function () { + return function() { xhr.abort(); }; }; diff --git a/src/lib/errors.js b/src/lib/errors.js index f82817e7f..94c38865f 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -2,8 +2,8 @@ var _ = require('lodash'); var utils = require('./utils'); var errors = module.exports; -var canCapture = (typeof Error.captureStackTrace === 'function'); -var canStack = !!(new Error()).stack; +var canCapture = typeof Error.captureStackTrace === 'function'; +var canStack = !!new Error().stack; function ErrorAbstract(msg, constructor, metadata) { this.message = msg; @@ -12,25 +12,26 @@ function ErrorAbstract(msg, constructor, metadata) { if (canCapture) { Error.captureStackTrace(this, constructor); - } - else if (canStack) { - this.stack = (new Error()).stack; - } - else { + } else if (canStack) { + this.stack = new Error().stack; + } else { this.stack = ''; } if (metadata) { _.assign(this, metadata); - this.toString = function () { + this.toString = function() { return msg + ' :: ' + JSON.stringify(metadata); }; - this.toJSON = function () { - return _.assign({ - msg: msg - }, metadata); + this.toJSON = function() { + return _.assign( + { + msg: msg, + }, + metadata + ); }; } } @@ -51,7 +52,11 @@ utils.inherits(errors.ConnectionFault, ErrorAbstract); * @param {String} [msg] - An error message that will probably end up in a log. */ errors.NoConnections = function NoConnections(msg) { - ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections); + ErrorAbstract.call( + this, + msg || 'No Living connections', + errors.NoConnections + ); }; utils.inherits(errors.NoConnections, ErrorAbstract); @@ -73,22 +78,28 @@ errors.RequestTimeout = function RequestTimeout(msg) { }; utils.inherits(errors.RequestTimeout, ErrorAbstract); - /** * Request Body could not be parsed * @param {String} [msg] - An error message that will probably end up in a log. */ errors.Serialization = function Serialization(msg) { - ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization); + ErrorAbstract.call( + this, + msg || 'Unable to parse/serialize body', + errors.Serialization + ); }; utils.inherits(errors.Serialization, ErrorAbstract); - /** * Thrown when a browser compatability issue is detected (cough, IE, cough) */ errors.RequestTypeError = function RequestTypeError(feature) { - ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError); + ErrorAbstract.call( + this, + 'Cross-domain AJAX requests ' + feature + ' are not supported', + errors.RequestTypeError + ); }; utils.inherits(errors.RequestTypeError, ErrorAbstract); @@ -134,7 +145,7 @@ var statusCodes = [ [504, 'Gateway Timeout'], [505, 'HTTPVersion Not Supported'], [506, 'Variant Also Negotiates'], - [510, 'Not Extended'] + [510, 'Not Extended'], ]; _.each(statusCodes, function createStatusCodeError(tuple) { @@ -163,7 +174,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) { return this; } - msg = [].concat(esErrObject.root_cause || []).reduce(function (memo, cause) { + msg = [].concat(esErrObject.root_cause || []).reduce(function(memo, cause) { if (memo) memo += ' (and) '; memo += '[' + cause.type + '] ' + cause.reason; @@ -186,27 +197,30 @@ _.each(statusCodes, function createStatusCodeError(tuple) { } utils.inherits(StatusCodeError, ErrorAbstract); - allNames.forEach(function (name) { + allNames.forEach(function(name) { errors[name] = StatusCodeError; }); }); - 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 ( + '{ ' + + _.map(v, function(subv, name) { + return name + '=' + print(subv); + }).join(' & ') + + ' }' + ); } finally { - path.pop() + path.pop(); } } else { - return JSON.stringify(v) + return JSON.stringify(v); } - }(data)) + })(data); } diff --git a/src/lib/host.js b/src/lib/host.js index 6482c0d4f..416feb1c9 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -18,12 +18,19 @@ if (typeof window !== 'undefined' && typeof window.location !== 'undefined') { btoa = window.btoa; } -btoa = btoa || function (data) { - return (new Buffer(data, 'utf8')).toString('base64'); -}; +btoa = + btoa || + function(data) { + return new Buffer(data, 'utf8').toString('base64'); + }; var urlParseFields = [ - 'protocol', 'hostname', 'pathname', 'port', 'auth', 'query' + 'protocol', + 'hostname', + 'pathname', + 'port', + 'auth', + 'query', ]; var simplify = ['host', 'path']; @@ -36,14 +43,14 @@ var sslDefaults = { ca: null, ciphers: null, rejectUnauthorized: false, - secureProtocol: null + secureProtocol: null, }; // simple reference used when formatting as a url // and defines when parsing from a string Host.defaultPorts = { http: 80, - https: 443 + https: 443, }; function Host(config, globalConfig) { @@ -59,7 +66,12 @@ function Host(config, globalConfig) { this.headers = null; this.suggestCompression = !!globalConfig.suggestCompression; - this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); + this.ssl = _.defaults( + {}, + config.ssl || {}, + globalConfig.ssl || {}, + sslDefaults + ); if (typeof config === 'string') { var firstColon = config.indexOf(':'); @@ -67,7 +79,10 @@ function Host(config, globalConfig) { var noSlash = firstSlash === -1; var portNoPath = firstColon > -1 && noSlash; var portWithPath = !portNoPath && firstColon < firstSlash; - if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) { + if ( + (noSlash || portNoPath || portWithPath) && + !startsWithProtocolRE.test(config) + ) { config = defaultProto + '//' + config; } config = _.pick(url.parse(config, false, true), urlParseFields); @@ -86,7 +101,7 @@ function Host(config, globalConfig) { if (_.isObject(config)) { // move hostname/portname to host/port semi-intelligently. - _.each(simplify, function (to) { + _.each(simplify, function(to) { var from = to + 'name'; if (config[from] && config[to]) { if (config[to].indexOf(config[from]) === 0) { @@ -102,7 +117,7 @@ function Host(config, globalConfig) { } if (!config.auth && globalConfig.httpAuth) { - config.auth = globalConfig.httpAuth + config.auth = globalConfig.httpAuth; } if (config.auth) { @@ -111,9 +126,12 @@ function Host(config, globalConfig) { delete config.auth; } - _.forOwn(config, _.bind(function (val, prop) { - if (val != null) this[prop] = _.clone(val); - }, this)); + _.forOwn( + config, + _.bind(function(val, prop) { + if (val != null) this[prop] = _.clone(val); + }, this) + ); // make sure the query string is parsed if (this.query === null) { @@ -143,7 +161,7 @@ function Host(config, globalConfig) { } } -Host.prototype.makeUrl = function (params) { +Host.prototype.makeUrl = function(params) { params = params || {}; // build the port var port = ''; @@ -164,14 +182,21 @@ Host.prototype.makeUrl = function (params) { var query = qs.stringify(this.getQuery(params.query)); if (this.host) { - return this.protocol + '://' + this.host + port + path + (query ? '?' + query : ''); + return ( + this.protocol + + '://' + + this.host + + port + + path + + (query ? '?' + query : '') + ); } else { return path + (query ? '?' + query : ''); } }; function objectPropertyGetter(prop, preOverride) { - return function (overrides) { + return function(overrides) { if (preOverride) { overrides = preOverride.call(this, overrides); } @@ -189,20 +214,22 @@ function objectPropertyGetter(prop, preOverride) { }; } -Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) { +Host.prototype.getHeaders = objectPropertyGetter('headers', function( + overrides +) { if (!this.suggestCompression) { return overrides; } return _.defaults(overrides || {}, { - 'Accept-Encoding': 'gzip,deflate' + 'Accept-Encoding': 'gzip,deflate', }); }); -Host.prototype.getQuery = objectPropertyGetter('query', function (query) { +Host.prototype.getQuery = objectPropertyGetter('query', function(query) { return typeof query === 'string' ? qs.parse(query) : query; }); -Host.prototype.toString = function () { +Host.prototype.toString = function() { return this.makeUrl(); }; diff --git a/src/lib/log.js b/src/lib/log.js index c13ef5ad8..e25a89c04 100644 --- a/src/lib/log.js +++ b/src/lib/log.js @@ -26,25 +26,29 @@ function Log(config) { var outputs; if (utils.isArrayOfStrings(config.log)) { - outputs = [{ - levels: config.log - }]; + outputs = [ + { + levels: config.log, + }, + ]; } else { - outputs = utils.createArray(config.log, function (val) { + outputs = utils.createArray(config.log, function(val) { if (_.isPlainObject(val)) { return val; } if (typeof val === 'string') { return { - level: val + level: val, }; } }); } if (!outputs) { - throw new TypeError('Invalid logging output config. Expected either a log level, array of log levels, ' + - 'a logger config object, or an array of logger config objects.'); + throw new TypeError( + 'Invalid logging output config. Expected either a log level, array of log levels, ' + + 'a logger config object, or an array of logger config objects.' + ); } for (i = 0; i < outputs.length; i++) { @@ -55,10 +59,12 @@ utils.inherits(Log, EventEmitter); Log.loggers = require('./loggers'); -Log.prototype.close = function () { +Log.prototype.close = function() { this.emit('closing'); if (this.listenerCount()) { - console.error('Something is still listening for log events, but the logger is closing.'); // eslint-disable-line no-console + console.error( + 'Something is still listening for log events, but the logger is closing.' + ); // eslint-disable-line no-console this.clearAllListeners(); } }; @@ -67,19 +73,17 @@ if (EventEmitter.prototype.listenerCount) { // If the event emitter implements it's own listenerCount method // we don't need to (newer nodes do this). Log.prototype.listenerCount = EventEmitter.prototype.listenerCount; -} -else if (EventEmitter.listenerCount) { +} else if (EventEmitter.listenerCount) { // some versions of node expose EventEmitter::listenerCount // which is more efficient the getting all listeners of a // specific type - Log.prototype.listenerCount = function (event) { + Log.prototype.listenerCount = function(event) { return EventEmitter.listenerCount(this, event); }; -} -else { +} else { // all other versions of node expose a #listeners() method, which returns // and array we have to count - Log.prototype.listenerCount = function (event) { + Log.prototype.listenerCount = function(event) { return this.listeners(event).length; }; } @@ -135,7 +139,7 @@ Log.levels = [ * @param {Integer} responseStatus - The status code returned from the response * @param {String} responseBody - The body of the response */ - 'trace' + 'trace', ]; /** @@ -149,7 +153,7 @@ Log.levels = [ * level, or an array of exact levels * @return {Array} - */ -Log.parseLevels = function (input) { +Log.parseLevels = function(input) { switch (typeof input) { case 'string': var i = _.indexOf(Log.levels, input); @@ -166,8 +170,12 @@ Log.parseLevels = function (input) { } /* fall through */ default: - throw new TypeError('invalid logging level ' + input + '. Expected zero or more of these options: ' + - Log.levels.join(', ')); + throw new TypeError( + 'invalid logging level ' + + input + + '. Expected zero or more of these options: ' + + Log.levels.join(', ') + ); } }; @@ -180,8 +188,8 @@ Log.parseLevels = function (input) { * @param {*} arrayish - An array like object that can be itterated by _.each * @return {String} - The final string. */ -Log.join = function (arrayish) { - return _.map(arrayish, function (item) { +Log.join = function(arrayish) { + return _.map(arrayish, function(item) { if (_.isPlainObject(item)) { return JSON.stringify(item, null, 2) + '\n'; } else { @@ -203,14 +211,19 @@ Log.join = function (arrayish) { * levels will be logged. * @return {Logger} */ -Log.prototype.addOutput = function (config) { +Log.prototype.addOutput = function(config) { config = config || {}; // force "levels" key config.levels = Log.parseLevels(config.levels || config.level || 'warning'); delete config.level; - var Logger = utils.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); + var Logger = utils.funcEnum( + config, + 'type', + Log.loggers, + process.browser ? 'console' : 'stdio' + ); return new Logger(this, config); }; @@ -221,13 +234,12 @@ Log.prototype.addOutput = function (config) { * @param {Error|String} error The Error to log * @return {Boolean} - True if any outputs accepted the message */ -Log.prototype.error = function (e) { +Log.prototype.error = function(e) { if (this.listenerCount('error')) { return this.emit('error', e instanceof Error ? e : new Error(e)); } }; - /** * Log a warning message * @@ -235,13 +247,12 @@ Log.prototype.error = function (e) { * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ -Log.prototype.warning = function (/* ...msg */) { +Log.prototype.warning = function(/* ...msg */) { if (this.listenerCount('warning')) { return this.emit('warning', Log.join(arguments)); } }; - /** * Log useful info about what's going on * @@ -249,7 +260,7 @@ Log.prototype.warning = function (/* ...msg */) { * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ -Log.prototype.info = function (/* ...msg */) { +Log.prototype.info = function(/* ...msg */) { if (this.listenerCount('info')) { return this.emit('info', Log.join(arguments)); } @@ -262,7 +273,7 @@ Log.prototype.info = function (/* ...msg */) { * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ -Log.prototype.debug = function (/* ...msg */) { +Log.prototype.debug = function(/* ...msg */) { if (this.listenerCount('debug')) { return this.emit('debug', Log.join(arguments)); } @@ -280,13 +291,34 @@ Log.prototype.debug = function (/* ...msg */) { * @param {String} responseStatus - HTTP status code * @return {Boolean} - True if any outputs accepted the message */ -Log.prototype.trace = function (method, requestUrl, body, responseBody, responseStatus) { +Log.prototype.trace = function( + method, + requestUrl, + body, + responseBody, + responseStatus +) { if (this.listenerCount('trace')) { - return this.emit('trace', Log.normalizeTraceArgs(method, requestUrl, body, responseBody, responseStatus)); + return this.emit( + 'trace', + Log.normalizeTraceArgs( + method, + requestUrl, + body, + responseBody, + responseStatus + ) + ); } }; -Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, responseStatus) { +Log.normalizeTraceArgs = function( + method, + requestUrl, + body, + responseBody, + responseStatus +) { if (typeof requestUrl === 'string') { requestUrl = url.parse(requestUrl, true, true); } else { @@ -306,7 +338,7 @@ Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, respo url: url.format(requestUrl), body: body, status: responseStatus, - response: responseBody + response: responseBody, }; }; diff --git a/src/lib/logger.js b/src/lib/logger.js index 07e428760..9e4edd6d9 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -27,28 +27,39 @@ function padNumToTen(n) { * Also, feel free to override this at the logger level. * @return {String} - Timestamp in ISO 8601 UTC */ -LoggerAbstract.prototype.timestamp = function () { +LoggerAbstract.prototype.timestamp = function() { var d = new Date(); - return d.getUTCFullYear() + '-' + - padNumToTen(d.getUTCMonth() + 1) + '-' + - padNumToTen(d.getUTCDate()) + 'T' + - padNumToTen(d.getUTCHours()) + ':' + - padNumToTen(d.getUTCMinutes()) + ':' + - padNumToTen(d.getUTCSeconds()) + 'Z'; + return ( + d.getUTCFullYear() + + '-' + + padNumToTen(d.getUTCMonth() + 1) + + '-' + + padNumToTen(d.getUTCDate()) + + 'T' + + padNumToTen(d.getUTCHours()) + + ':' + + padNumToTen(d.getUTCMinutes()) + + ':' + + padNumToTen(d.getUTCSeconds()) + + 'Z' + ); }; function indent(text, spaces) { var space = utils.repeat(' ', spaces || 2); - return (text || '').split(/\r?\n/).map(function (line) { - return space + line; - }).join('\n'); + return (text || '') + .split(/\r?\n/) + .map(function(line) { + return space + line; + }) + .join('\n'); } -LoggerAbstract.prototype.format = function (label, message) { +LoggerAbstract.prototype.format = function(label, message) { return label + ': ' + this.timestamp() + '\n' + indent(message) + '\n\n'; }; -LoggerAbstract.prototype.write = function () { +LoggerAbstract.prototype.write = function() { throw new Error('This should be overwritten by the logger'); }; @@ -60,20 +71,23 @@ LoggerAbstract.prototype.write = function () { * @param {Integer} level - The max log level that this logger should listen to * @return {undefined} */ -LoggerAbstract.prototype.setupListeners = function (levels) { +LoggerAbstract.prototype.setupListeners = function(levels) { this.cleanUpListeners(); this.listeningLevels = []; - _.each(levels, _.bind(function (level) { - var fnName = 'on' + utils.ucfirst(level); - if (this.bound[fnName]) { - this.listeningLevels.push(level); - this.log.on(level, this.bound[fnName]); - } else { - throw new Error('Unable to listen for level "' + level + '"'); - } - }, this)); + _.each( + levels, + _.bind(function(level) { + var fnName = 'on' + utils.ucfirst(level); + if (this.bound[fnName]) { + this.listeningLevels.push(level); + this.log.on(level, this.bound[fnName]); + } else { + throw new Error('Unable to listen for level "' + level + '"'); + } + }, this) + ); }; /** @@ -83,10 +97,13 @@ LoggerAbstract.prototype.setupListeners = function (levels) { * @private * @return {undefined} */ -LoggerAbstract.prototype.cleanUpListeners = utils.handler(function () { - _.each(this.listeningLevels, _.bind(function (level) { - this.log.removeListener(level, this.bound['on' + utils.ucfirst(level)]); - }, this)); +LoggerAbstract.prototype.cleanUpListeners = utils.handler(function() { + _.each( + this.listeningLevels, + _.bind(function(level) { + this.log.removeListener(level, this.bound['on' + utils.ucfirst(level)]); + }, this) + ); }); /** @@ -97,8 +114,8 @@ LoggerAbstract.prototype.cleanUpListeners = utils.handler(function () { * @param {Error} e - The Error object to log * @return {undefined} */ -LoggerAbstract.prototype.onError = utils.handler(function (e) { - this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack); +LoggerAbstract.prototype.onError = utils.handler(function(e) { + this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack); }); /** @@ -109,7 +126,7 @@ LoggerAbstract.prototype.onError = utils.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onWarning = utils.handler(function (msg) { +LoggerAbstract.prototype.onWarning = utils.handler(function(msg) { this.write('WARNING', msg); }); @@ -121,7 +138,7 @@ LoggerAbstract.prototype.onWarning = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onInfo = utils.handler(function (msg) { +LoggerAbstract.prototype.onInfo = utils.handler(function(msg) { this.write('INFO', msg); }); @@ -133,7 +150,7 @@ LoggerAbstract.prototype.onInfo = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onDebug = utils.handler(function (msg) { +LoggerAbstract.prototype.onDebug = utils.handler(function(msg) { this.write('DEBUG', msg); }); @@ -145,16 +162,25 @@ LoggerAbstract.prototype.onDebug = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onTrace = utils.handler(function (requestDetails) { +LoggerAbstract.prototype.onTrace = utils.handler(function(requestDetails) { this.write('TRACE', this._formatTraceMessage(requestDetails)); }); -LoggerAbstract.prototype._formatTraceMessage = function (req) { - return '-> ' + req.method + ' ' + req.url + '\n' + - this._prettyJson(req.body) + '\n' + - '<- ' + req.status + '\n' + - this._prettyJson(req.response); -/* +LoggerAbstract.prototype._formatTraceMessage = function(req) { + return ( + '-> ' + + req.method + + ' ' + + req.url + + '\n' + + this._prettyJson(req.body) + + '\n' + + '<- ' + + req.status + + '\n' + + this._prettyJson(req.response) + ); + /* -> GET https://sldfkjsdlfksjdf:9200/slsdkfjlxckvxhclks?sdlkj=sdlfkje { asdflksjdf @@ -167,7 +193,7 @@ LoggerAbstract.prototype._formatTraceMessage = function (req) { */ }; -LoggerAbstract.prototype._prettyJson = function (body) { +LoggerAbstract.prototype._prettyJson = function(body) { try { if (typeof body === 'string') { body = JSON.parse(body); diff --git a/src/lib/loggers/browser_index.js b/src/lib/loggers/browser_index.js index 51b651356..ee6f270b7 100644 --- a/src/lib/loggers/browser_index.js +++ b/src/lib/loggers/browser_index.js @@ -1,3 +1,3 @@ module.exports = { - console: require('./console') + console: require('./console'), }; diff --git a/src/lib/loggers/console.js b/src/lib/loggers/console.js index 7b268ca4a..76f2abb22 100644 --- a/src/lib/loggers/console.js +++ b/src/lib/loggers/console.js @@ -29,12 +29,12 @@ utils.inherits(Console, LoggerAbstract); * * @param {Array} levels - The levels that we should be listeneing for */ -Console.prototype.setupListeners = function (levels) { +Console.prototype.setupListeners = function(levels) { // call the super method LoggerAbstract.prototype.setupListeners.call(this, levels); }; -Console.prototype.write = function (label, message, to) { +Console.prototype.write = function(label, message, to) { if (console[to]) { console[to](this.format(label, message)); } @@ -48,7 +48,7 @@ Console.prototype.write = function (label, message, to) { * @param {Error} e - The Error object to log * @return {undefined} */ -Console.prototype.onError = utils.handler(function (e) { +Console.prototype.onError = utils.handler(function(e) { var to = console.error ? 'error' : 'log'; this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to); }); @@ -61,7 +61,7 @@ Console.prototype.onError = utils.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onWarning = utils.handler(function (msg) { +Console.prototype.onWarning = utils.handler(function(msg) { this.write('WARNING', msg, console.warn ? 'warn' : 'log'); }); @@ -73,7 +73,7 @@ Console.prototype.onWarning = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onInfo = utils.handler(function (msg) { +Console.prototype.onInfo = utils.handler(function(msg) { this.write('INFO', msg, console.info ? 'info' : 'log'); }); @@ -85,7 +85,7 @@ Console.prototype.onInfo = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onDebug = utils.handler(function (msg) { +Console.prototype.onDebug = utils.handler(function(msg) { this.write('DEBUG', msg, console.debug ? 'debug' : 'log'); }); /** @@ -95,6 +95,6 @@ Console.prototype.onDebug = utils.handler(function (msg) { * @private * @return {undefined} */ -Console.prototype.onTrace = utils.handler(function (msg) { +Console.prototype.onTrace = utils.handler(function(msg) { this.write('TRACE', this._formatTraceMessage(msg), 'log'); }); diff --git a/src/lib/loggers/file.js b/src/lib/loggers/file.js index 8f3f54f8f..0c650ec9f 100755 --- a/src/lib/loggers/file.js +++ b/src/lib/loggers/file.js @@ -24,14 +24,14 @@ function File(log, config) { // yahoo! config.stream = fs.createWriteStream(this.path, { flags: 'a', - encoding: 'utf8' + encoding: 'utf8', }); StreamLogger.call(this, log, config); } utils.inherits(File, StreamLogger); -File.prototype.onProcessExit = utils.handler(function () { +File.prototype.onProcessExit = utils.handler(function() { var toWrite = utils.getUnwrittenFromStream(this.stream); if (toWrite) { fs.appendFileSync(this.path, toWrite); diff --git a/src/lib/loggers/index.js b/src/lib/loggers/index.js index fb75cfb2d..db9b87b06 100644 --- a/src/lib/loggers/index.js +++ b/src/lib/loggers/index.js @@ -3,5 +3,5 @@ module.exports = { file: require('./file'), stream: require('./stream'), stdio: require('./stdio'), - tracer: require('./tracer') + tracer: require('./tracer'), }; diff --git a/src/lib/loggers/stdio.js b/src/lib/loggers/stdio.js index fe22fc791..9900ee544 100755 --- a/src/lib/loggers/stdio.js +++ b/src/lib/loggers/stdio.js @@ -25,7 +25,7 @@ var defaultColors = { warning: chalk.yellow.bold, info: chalk.cyan.bold, debug: chalk.magenta.bold, - trace: chalk.white.bold + trace: chalk.white.bold, }; function Stdio(log, config) { @@ -50,7 +50,7 @@ utils.inherits(Stdio, LoggerAbstract); * @param {*} what - The message to log * @return {undefined} */ -Stdio.prototype.write = function (label, message, to, colorize) { +Stdio.prototype.write = function(label, message, to, colorize) { label = 'Elasticsearch ' + label; if (this.color) { label = colorize(label); @@ -66,8 +66,13 @@ Stdio.prototype.write = function (label, message, to, colorize) { * @param {Error} e - The Error object to log * @return {undefined} */ -Stdio.prototype.onError = utils.handler(function (e) { - this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack, process.stderr, this.colors.error); +Stdio.prototype.onError = utils.handler(function(e) { + this.write( + e.name === 'Error' ? 'ERROR' : e.name, + e.stack, + process.stderr, + this.colors.error + ); }); /** @@ -78,7 +83,7 @@ Stdio.prototype.onError = utils.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onWarning = utils.handler(function (msg) { +Stdio.prototype.onWarning = utils.handler(function(msg) { this.write('WARNING', msg, process.stderr, this.colors.warning); }); @@ -90,7 +95,7 @@ Stdio.prototype.onWarning = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onInfo = utils.handler(function (msg) { +Stdio.prototype.onInfo = utils.handler(function(msg) { this.write('INFO', msg, process.stdout, this.colors.info); }); @@ -102,7 +107,7 @@ Stdio.prototype.onInfo = utils.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onDebug = utils.handler(function (msg) { +Stdio.prototype.onDebug = utils.handler(function(msg) { this.write('DEBUG', msg, process.stdout, this.colors.debug); }); @@ -113,6 +118,11 @@ Stdio.prototype.onDebug = utils.handler(function (msg) { * @private * @return {undefined} */ -Stdio.prototype.onTrace = utils.handler(function (message) { - this.write('TRACE', this._formatTraceMessage(message), process.stdout, this.colors.trace); +Stdio.prototype.onTrace = utils.handler(function(message) { + this.write( + 'TRACE', + this._formatTraceMessage(message), + process.stdout, + this.colors.trace + ); }); diff --git a/src/lib/loggers/stream.js b/src/lib/loggers/stream.js index b97a9d508..9b8b68041 100755 --- a/src/lib/loggers/stream.js +++ b/src/lib/loggers/stream.js @@ -28,25 +28,27 @@ function Stream(log, config) { } utils.inherits(Stream, LoggerAbstract); -Stream.prototype.cleanUpListeners = utils.handler(function () { +Stream.prototype.cleanUpListeners = utils.handler(function() { process.removeListener('exit', this.bound.onProcessExit); LoggerAbstract.prototype.cleanUpListeners.call(this); }); // flush the write buffer to stderr synchronously -Stream.prototype.onProcessExit = utils.handler(function () { +Stream.prototype.onProcessExit = utils.handler(function() { // process is dying, lets manually flush the buffer synchronously to stderr. var unwritten = utils.getUnwrittenFromStream(this.stream); if (unwritten) { - console.error('Log stream did not get to finish writing. Flushing to stderr'); + console.error( + 'Log stream did not get to finish writing. Flushing to stderr' + ); console.error(unwritten); } }); -Stream.prototype.write = function (label, message) { +Stream.prototype.write = function(label, message) { this.stream.write(this.format(label, message), 'utf8'); }; -Stream.prototype.close = function () { +Stream.prototype.close = function() { this.stream.end(); }; diff --git a/src/lib/loggers/tracer.js b/src/lib/loggers/tracer.js index 2d1494fab..bd0510093 100755 --- a/src/lib/loggers/tracer.js +++ b/src/lib/loggers/tracer.js @@ -22,7 +22,9 @@ function Tracer(log, config) { if (config.path === false) { config.stream = process.stderr; } else { - config.stream = fs.createWriteStream(config.path || 'elasticsearch-tracer.log'); + config.stream = fs.createWriteStream( + config.path || 'elasticsearch-tracer.log' + ); } this.curlHost = config.curlHost || 'localhost'; @@ -32,12 +34,21 @@ function Tracer(log, config) { } utils.inherits(Tracer, StreamLogger); -var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query']; +var usefulUrlFields = [ + 'protocol', + 'slashes', + 'port', + 'hostname', + 'pathname', + 'query', +]; -Tracer.prototype._formatTraceMessage = function (req) { +Tracer.prototype._formatTraceMessage = function(req) { var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields); - var originalHost = url.format(_.pick(reqUrl, ['protocol', 'hostname', 'port'])); + var originalHost = url.format( + _.pick(reqUrl, ['protocol', 'hostname', 'port']) + ); reqUrl.port = this.curlPort; reqUrl.hostname = this.curlHost; @@ -45,28 +56,36 @@ Tracer.prototype._formatTraceMessage = function (req) { /* jshint quotmark: double */ var curlCall = - '# ' + originalHost + '\n' + - "curl '" + url.format(reqUrl).replace(/'/g, "\\'") + "' -X" + req.method.toUpperCase() + + '# ' + + originalHost + + '\n' + + "curl '" + + url.format(reqUrl).replace(/'/g, "\\'") + + "' -X" + + req.method.toUpperCase() + (req.body ? " -d '" + this._prettyJson(req.body) + "'" : ''); /* jshint quotmark: single */ return { curl: curlCall, - msg: '-> ' + req.status + '\n' + req.response + msg: '-> ' + req.status + '\n' + req.response, }; }; function comment(str) { - return _.map(str.split(/\r?\n/g), function (line) { + return _.map(str.split(/\r?\n/g), function(line) { return '# ' + line; }).join('\n'); } -Tracer.prototype.write = function (label, msg) { +Tracer.prototype.write = function(label, msg) { var lead = comment(label + ': ' + this.timestamp()) + '\n'; if (typeof msg === 'string') { this.stream.write(lead + comment(msg) + '\n\n', 'utf8'); } else { - this.stream.write(lead + msg.curl + '\n' + comment(msg.msg) + '\n\n', 'utf8'); + this.stream.write( + lead + msg.curl + '\n' + comment(msg.msg) + '\n\n', + 'utf8' + ); } }; diff --git a/src/lib/nodes_to_host.js b/src/lib/nodes_to_host.js index 838c89d49..e3fc023cf 100644 --- a/src/lib/nodes_to_host.js +++ b/src/lib/nodes_to_host.js @@ -3,56 +3,63 @@ var _ = require('lodash'); var extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/; function makeNodeParser(hostProp) { - return function (nodes) { - return _.transform(nodes, function (hosts, node, id) { - var address = _.get(node, hostProp) - if (!address) return; + return function(nodes) { + return _.transform( + nodes, + function(hosts, node, id) { + var address = _.get(node, hostProp); + if (!address) return; - var host = { - host: undefined, - port: undefined, - _meta: { - id: id, - name: node.name, - version: node.version + var host = { + host: undefined, + port: undefined, + _meta: { + id: id, + name: node.name, + version: node.version, + }, + }; + + var malformedError = new Error( + 'Malformed ' + + hostProp + + '.' + + ' Got ' + + JSON.stringify(address) + + ' and expected it to match "{hostname?}/{ip}:{port}".' + ); + + var matches1x = extractHostPartsRE1x.exec(address); + if (matches1x) { + host.host = matches1x[1] || matches1x[2]; + host.port = parseInt(matches1x[3], 10); + hosts.push(host); + return; } - }; - var malformedError = new Error( - 'Malformed ' + hostProp + '.' + - ' Got ' + JSON.stringify(address) + - ' and expected it to match "{hostname?}/{ip}:{port}".' - ); + if (address.indexOf('/') > -1) { + var withHostParts = address.split('/'); + if (withHostParts.length !== 2) throw malformedError; - var matches1x = extractHostPartsRE1x.exec(address); - if (matches1x) { - host.host = matches1x[1] || matches1x[2]; - host.port = parseInt(matches1x[3], 10); + host.host = withHostParts.shift(); + address = withHostParts.shift(); + } + + if (address.indexOf(':') < 0) { + throw malformedError; + } + + var addressParts = address.split(':'); + if (addressParts.length !== 2) { + throw malformedError; + } + + host.host = host.host || addressParts[0]; + host.port = parseInt(addressParts[1], 10); hosts.push(host); - return; - } - - if (address.indexOf('/') > -1) { - var withHostParts = address.split('/'); - if (withHostParts.length !== 2) throw malformedError; - - host.host = withHostParts.shift(); - address = withHostParts.shift(); - } - - if (address.indexOf(':') < 0) { - throw malformedError; - } - - var addressParts = address.split(':'); - if (addressParts.length !== 2) { - throw malformedError; - } - - host.host = host.host || addressParts[0]; - host.port = parseInt(addressParts[1], 10); - hosts.push(host); - }, []); + }, + [] + ); }; } diff --git a/src/lib/selectors/index.js b/src/lib/selectors/index.js index ab302b203..e22ec5c53 100644 --- a/src/lib/selectors/index.js +++ b/src/lib/selectors/index.js @@ -1,4 +1,4 @@ module.exports = { random: require('./random'), - roundRobin: require('./round_robin') + roundRobin: require('./round_robin'), }; diff --git a/src/lib/selectors/round_robin.js b/src/lib/selectors/round_robin.js index e7de6858c..5375fed31 100644 --- a/src/lib/selectors/round_robin.js +++ b/src/lib/selectors/round_robin.js @@ -6,7 +6,7 @@ * @param {Array} connections - The list of connections that this selector needs to choose from * @return {Connection} - The selected connection */ -module.exports = function (connections) { +module.exports = function(connections) { var connection = connections[0]; connections.push(connections.shift()); return connection; diff --git a/src/lib/serializers/angular.js b/src/lib/serializers/angular.js index cba397ff9..99854e142 100644 --- a/src/lib/serializers/angular.js +++ b/src/lib/serializers/angular.js @@ -6,7 +6,7 @@ function AngularSerializer() {} utils.inherits(AngularSerializer, JsonSerializer); // mimic the JsonSerializer's encode method, but use angular's toJson instead -AngularSerializer.prototype.encode = function (val) { +AngularSerializer.prototype.encode = function(val) { switch (typeof val) { case 'string': return val; @@ -14,7 +14,7 @@ AngularSerializer.prototype.encode = function (val) { if (val) return angular.toJson(val); /* falls through */ default: - return; + return undefined; } }; diff --git a/src/lib/serializers/index.js b/src/lib/serializers/index.js index ba51ae93a..50447e21a 100644 --- a/src/lib/serializers/index.js +++ b/src/lib/serializers/index.js @@ -1,4 +1,4 @@ module.exports = { angular: require('./angular'), - json: require('./json') + json: require('./json'), }; diff --git a/src/lib/serializers/json.js b/src/lib/serializers/json.js index 5a6c86b4e..cb8d87caf 100755 --- a/src/lib/serializers/json.js +++ b/src/lib/serializers/json.js @@ -14,7 +14,7 @@ function Json() {} * see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify about other params * @return {String|Error} - A string is always returned, unless an error occured. then it will be that error. */ -Json.prototype.serialize = function (val, replacer, spaces) { +Json.prototype.serialize = function(val, replacer, spaces) { switch (typeof val) { case 'string': return val; @@ -28,7 +28,7 @@ Json.prototype.serialize = function (val, replacer, spaces) { } /* falls through */ default: - return; + return undefined; } }; @@ -39,7 +39,7 @@ Json.prototype.serialize.contentType = 'application/json'; * @param {String} str - the string to parse * @return {[type]} */ -Json.prototype.deserialize = function (str) { +Json.prototype.deserialize = function(str) { if (typeof str === 'string') { try { return JSON.parse(str); @@ -47,8 +47,9 @@ Json.prototype.deserialize = function (str) { } }; -Json.prototype.bulkBody = function (val) { - var body = '', i; +Json.prototype.bulkBody = function(val) { + var body = ''; + var i; if (_.isArray(val)) { for (i = 0; i < val.length; i++) { @@ -58,7 +59,9 @@ Json.prototype.bulkBody = function (val) { // make sure the string ends in a new line body = val + (val[val.length - 1] === '\n' ? '' : '\n'); } else { - throw new TypeError('Bulk body should either be an Array of commands/string, or a String'); + throw new TypeError( + 'Bulk body should either be an Array of commands/string, or a String' + ); } return body; diff --git a/src/lib/transport.js b/src/lib/transport.js index 052015512..3f69f7d1d 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -15,51 +15,77 @@ function Transport(config) { var self = this; config = self._config = config || {}; - var LogClass = (typeof config.log === 'function') ? config.log : require('./log'); + var LogClass = + typeof config.log === 'function' ? config.log : require('./log'); config.log = self.log = new LogClass(config); // setup the connection pool - var ConnectionPool = utils.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); + var ConnectionPool = utils.funcEnum( + config, + 'connectionPool', + Transport.connectionPools, + 'main' + ); self.connectionPool = new ConnectionPool(config); // setup the serializer - var Serializer = utils.funcEnum(config, 'serializer', Transport.serializers, 'json'); + var Serializer = utils.funcEnum( + config, + 'serializer', + Transport.serializers, + 'json' + ); self.serializer = new Serializer(config); // setup the nodesToHostCallback - self.nodesToHostCallback = utils.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); + self.nodesToHostCallback = utils.funcEnum( + config, + 'nodesToHostCallback', + Transport.nodesToHostCallbacks, + 'main' + ); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; // setup endpoint to use for sniffing - self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') ? config.sniffEndpoint : '/_nodes/_all/http'; + self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') + ? config.sniffEndpoint + : '/_nodes/_all/http'; // setup requestTimeout default - self.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000; - self.pingTimeout = config.hasOwnProperty('pingTimeout') ? config.pingTimeout : 3000; + self.requestTimeout = config.hasOwnProperty('requestTimeout') + ? config.requestTimeout + : 30000; + self.pingTimeout = config.hasOwnProperty('pingTimeout') + ? config.pingTimeout + : 3000; if (config.hasOwnProperty('defer')) { self.defer = config.defer; } // randomizeHosts option - var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true; + var randomizeHosts = config.hasOwnProperty('randomizeHosts') + ? !!config.randomizeHosts + : true; if (config.host) { config.hosts = config.host; } if (config.hosts) { - var hostsConfig = utils.createArray(config.hosts, function (val) { + var hostsConfig = utils.createArray(config.hosts, function(val) { if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { return val; } }); if (!hostsConfig) { - throw new TypeError('Invalid hosts config. Expected a URL, an array of urls, a host config object, ' + - 'or an array of host config objects.'); + throw new TypeError( + 'Invalid hosts config. Expected a URL, an array of urls, a host config object, ' + + 'or an array of host config objects.' + ); } if (randomizeHosts) { @@ -72,7 +98,8 @@ function Transport(config) { if (config.hasOwnProperty('sniffedNodesProtocol')) { self.sniffedNodesProtocol = config.sniffedNodesProtocol || null; } else { - self.sniffedNodesProtocol = findCommonProtocol(self.connectionPool.getAllHosts()) || null; + self.sniffedNodesProtocol = + findCommonProtocol(self.connectionPool.getAllHosts()) || null; } if (config.hasOwnProperty('sniffedNodesFilterPath')) { @@ -104,25 +131,25 @@ function Transport(config) { } Transport.connectionPools = { - main: require('./connection_pool') + main: require('./connection_pool'), }; Transport.serializers = require('./serializers'); Transport.nodesToHostCallbacks = { - main: require('./nodes_to_host') + main: require('./nodes_to_host'), }; -Transport.prototype.defer = function () { +Transport.prototype.defer = function() { if (typeof Promise === 'undefined') { 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' - ) + 'either specify the `defer` configuration or include a global Promise shim' + ); } var defer = {}; - defer.promise = new Promise(function (resolve, reject) { + defer.promise = new Promise(function(resolve, reject) { defer.resolve = resolve; defer.reject = reject; }); @@ -146,7 +173,7 @@ Transport.prototype.defer = function () { * @param {String} params.body - The body of the HTTP request * @param {Function} cb - A function to call back with (error, responseBody, responseStatus) */ -Transport.prototype.request = function (params, cb) { +Transport.prototype.request = function(params, cb) { var self = this; var remainingRetries = this.maxRetries; var requestTimeout = this.requestTimeout; @@ -159,9 +186,11 @@ Transport.prototype.request = function (params, cb) { var 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) { - headers[String(name).toLowerCase()] = val; - }); + var headers = !params.headers + ? {} + : _.transform(params.headers, function(headers, val, name) { + headers[String(name).toLowerCase()] = val; + }); self.log.debug('starting request', params); @@ -172,7 +201,7 @@ Transport.prototype.request = function (params, cb) { cb = process.domain.bind(cb); } ret = { - abort: abortRequest + abort: abortRequest, }; } else { defer = this.defer(); @@ -181,7 +210,10 @@ Transport.prototype.request = function (params, cb) { } if (body && params.method === 'GET') { - utils.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); + utils.nextTick( + respond, + new TypeError('Body can not be sent with method "GET"') + ); return ret; } @@ -206,7 +238,8 @@ Transport.prototype.request = function (params, cb) { const pingRequest = params.path === '/' && params.method === 'HEAD'; if (pingRequest) { - const requestParam = params.hasOwnProperty('requestTimeout') && params.requestTimeout; + const requestParam = + params.hasOwnProperty('requestTimeout') && params.requestTimeout; requestTimeout = requestParam || this.pingTimeout; } @@ -215,7 +248,7 @@ Transport.prototype.request = function (params, cb) { path: params.path || '/', query: params.query, body: body, - headers: headers + headers: headers, }; function sendReqWithConnection(err, _connection) { @@ -258,8 +291,7 @@ Transport.prototype.request = function (params, cb) { ' ' + connection.host.makeUrl(params.req) + (errMsg.length ? ' => ' : '') + - errMsg - ; + errMsg; if (remainingRetries) { remainingRetries--; @@ -282,7 +314,10 @@ Transport.prototype.request = function (params, cb) { self._timeout(requestTimeoutId); var parsedBody; - var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json')); + var isJson = + !headers || + (headers['content-type'] && + ~headers['content-type'].indexOf('application/json')); if (!err && body) { if (isJson) { @@ -298,11 +333,10 @@ Transport.prototype.request = function (params, cb) { // does the response represent an error? if ( - (!err || err instanceof errors.Serialization) - && (status < 200 || status >= 300) - && (!params.ignore || !_.includes(params.ignore, status)) + (!err || err instanceof errors.Serialization) && + (status < 200 || status >= 300) && + (!params.ignore || !_.includes(params.ignore, status)) ) { - var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); errorMetadata.statusCode = status; errorMetadata.response = body; @@ -358,8 +392,12 @@ Transport.prototype.request = function (params, cb) { } if (requestTimeout && requestTimeout !== Infinity) { - requestTimeoutId = this._timeout(function () { - respond(new errors.RequestTimeout('Request Timeout after ' + requestTimeout + 'ms')); + requestTimeoutId = this._timeout(function() { + respond( + new errors.RequestTimeout( + 'Request Timeout after ' + requestTimeout + 'ms' + ) + ); abortRequest(); }, requestTimeout); } @@ -373,20 +411,20 @@ Transport.prototype.request = function (params, cb) { return ret; }; -Transport.prototype._timeout = function (cb, delay) { +Transport.prototype._timeout = function(cb, delay) { if (this.closed) return; var id; var timers = this._timers || (this._timers = []); - if ('function' !== typeof cb) { + if (typeof cb !== 'function') { id = cb; cb = void 0; } if (cb) { // set the timer - id = setTimeout(function () { + id = setTimeout(function() { _.pull(timers, id); cb(); }, delay); @@ -411,7 +449,7 @@ Transport.prototype._timeout = function (cb, delay) { * * @param {Function} cb - Function to call back once complete */ -Transport.prototype.sniff = function (cb) { +Transport.prototype.sniff = function(cb) { var self = this; var nodesToHostCallback = this.nodesToHostCallback; var log = this.log; @@ -421,30 +459,39 @@ Transport.prototype.sniff = function (cb) { // make cb a function if it isn't cb = typeof cb === 'function' ? cb : _.noop; - this.request({ - path: this.sniffEndpoint, - query: { filter_path: sniffedNodesFilterPath }, - method: 'GET' - }, function (err, resp, status) { - if (!err && resp && resp.nodes) { - var hostsConfigs; + this.request( + { + path: this.sniffEndpoint, + query: { filter_path: sniffedNodesFilterPath }, + method: 'GET', + }, + function(err, resp, status) { + if (!err && resp && resp.nodes) { + var hostsConfigs; - try { - hostsConfigs = nodesToHostCallback(resp.nodes); - } catch (e) { - log.error(new Error('Unable to convert node list from ' + self.sniffEndpoint + - ' to hosts durring sniff. Encountered error:\n' + (e.stack || e.message))); - return; + try { + hostsConfigs = nodesToHostCallback(resp.nodes); + } catch (e) { + log.error( + new Error( + 'Unable to convert node list from ' + + self.sniffEndpoint + + ' to hosts durring sniff. Encountered error:\n' + + (e.stack || e.message) + ) + ); + return; + } + + _.forEach(hostsConfigs, function(hostConfig) { + if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol; + }); + + self.setHosts(hostsConfigs); } - - _.forEach(hostsConfigs, function (hostConfig) { - if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol; - }); - - self.setHosts(hostsConfigs); + cb(err, resp, status); } - cb(err, resp, status); - }); + ); }; /** @@ -453,18 +500,20 @@ Transport.prototype.sniff = function (cb) { * @param {Array} hostsConfigs - an array of Hosts, or configuration objects * that will be used to create Host objects. */ -Transport.prototype.setHosts = function (hostsConfigs) { +Transport.prototype.setHosts = function(hostsConfigs) { var globalConfig = this._config; - this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) { - return (conf instanceof Host) ? conf : new Host(conf, globalConfig); - })); + this.connectionPool.setHosts( + _.map(hostsConfigs, function(conf) { + return conf instanceof Host ? conf : new Host(conf, globalConfig); + }) + ); }; /** * Close the Transport, which closes the logs and connection pool * @return {[type]} [description] */ -Transport.prototype.close = function () { +Transport.prototype.close = function() { this.log.close(); this.closed = true; _.each(this._timers, clearTimeout); diff --git a/src/lib/transport/find_common_protocol.js b/src/lib/transport/find_common_protocol.js index b3843ae84..73c288254 100644 --- a/src/lib/transport/find_common_protocol.js +++ b/src/lib/transport/find_common_protocol.js @@ -1,6 +1,6 @@ var _ = require('lodash'); -module.exports = function (hosts) { +module.exports = function(hosts) { if (_.isEmpty(hosts)) return false; var commonProtocol = hosts.shift().protocol; diff --git a/src/lib/transport/sniff_on_connection_fault.js b/src/lib/transport/sniff_on_connection_fault.js index b9d084996..1aa17961d 100644 --- a/src/lib/transport/sniff_on_connection_fault.js +++ b/src/lib/transport/sniff_on_connection_fault.js @@ -1,6 +1,5 @@ var utils = require('../utils'); - /** * Patch the transport's connection pool to schedule a sniff after a connection fails. * When a connection fails for the first time it will schedule a sniff 1 second in the @@ -17,22 +16,22 @@ module.exports = function setupSniffOnConnectionFault(transport) { // do the actual sniff, if the sniff is unable to // connect to a node this function will be called again by the connectionPool - var work = function () { + var work = function() { work.timerId = transport._timeout(work.timerId); transport.sniff(); }; // create a function that will count down to a // point n milliseconds into the future - var countdownTo = function (ms) { + var countdownTo = function(ms) { var start = utils.now(); - return function () { + return function() { return start - ms; }; }; // overwrite the function, but still call it - pool._onConnectionDied = function (connection, wasAlreadyDead) { + pool._onConnectionDied = function(connection, wasAlreadyDead) { var ret = originalOnDied.call(pool, connection, wasAlreadyDead); // clear the failures if this is the first failure we have seen @@ -53,7 +52,7 @@ module.exports = function setupSniffOnConnectionFault(transport) { return ret; }; - pool._onConnectionDied.restore = function () { + pool._onConnectionDied.restore = function() { pool._onConnectionDied = originalOnDied; }; }; diff --git a/src/lib/utils.js b/src/lib/utils.js index 520d0a7c2..26062c7dd 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -18,12 +18,11 @@ utils.inherits = nodeUtils.inherits; * @param {Array} arr - An array to check * @return {Boolean} */ -utils.isArrayOfStrings = function (arr) { +utils.isArrayOfStrings = function(arr) { // quick shallow check of arrays return _.isArray(arr) && _.every(arr.slice(0, 10), _.isString); }; - /** * Capitalize the first letter of a word * @@ -31,7 +30,7 @@ utils.isArrayOfStrings = function (arr) { * @param {string} word - The word to transform * @return {string} */ -utils.ucfirst = function (word) { +utils.ucfirst = function(word) { return word[0].toUpperCase() + word.substring(1).toLowerCase(); }; @@ -41,7 +40,7 @@ utils.ucfirst = function (word) { * @return {Function} */ function adjustWordCase(firstWordCap, otherWordsCap, sep) { - return function (string) { + return function(string) { var i = 0; var words = []; var word = ''; @@ -65,10 +64,12 @@ function adjustWordCase(firstWordCap, otherWordsCap, sep) { if (lower && word.length) { word += c; } else { - if ((!words.length && firstWordCap) || (words.length && otherWordsCap)) { + if ( + (!words.length && firstWordCap) || + (words.length && otherWordsCap) + ) { word = c.toUpperCase(); - } - else { + } else { word = c.toLowerCase(); } } @@ -118,7 +119,7 @@ utils.snakeCase = adjustWordCase(false, false, '_'); * @param any {*} - Something or nothing * @returns {string} */ -utils.toUpperString = function (any) { +utils.toUpperString = function(any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -136,7 +137,7 @@ utils.toUpperString = function (any) { * @param {*} val * @return {Boolean} */ -utils.isNumeric = function (val) { +utils.isNumeric = function(val) { return typeof val !== 'object' && val - parseFloat(val) >= 0; }; @@ -150,7 +151,7 @@ var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/; * @param {String} val * @return {Boolean} */ -utils.isInterval = function (val) { +utils.isInterval = function(val) { return !!(val.match && val.match(intervalRE)); }; @@ -163,8 +164,8 @@ utils.isInterval = function (val) { * @param {Number} times - Times the string should be repeated * @return {String} */ -utils.repeat = function (what, times) { - return (new Array(times + 1)).join(what); +utils.repeat = function(what, times) { + return new Array(times + 1).join(what); }; /** @@ -176,7 +177,7 @@ utils.repeat = function (what, times) { * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func * @returns {*} - the return value of func */ -utils.applyArgs = function (func, context, args, sliceIndex) { +utils.applyArgs = function(func, context, args, sliceIndex) { sliceIndex = sliceIndex || 0; switch (args.length - sliceIndex) { case 0: @@ -186,12 +187,29 @@ utils.applyArgs = function (func, context, args, sliceIndex) { case 2: return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex]); case 3: - return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex]); + return func.call( + context, + args[0 + sliceIndex], + args[1 + sliceIndex], + args[2 + sliceIndex] + ); case 4: - return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex], args[3 + sliceIndex]); + return func.call( + context, + args[0 + sliceIndex], + args[1 + sliceIndex], + args[2 + sliceIndex], + args[3 + sliceIndex] + ); case 5: - return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], - args[2 + sliceIndex], args[3 + sliceIndex], args[4 + sliceIndex]); + return func.call( + context, + args[0 + sliceIndex], + args[1 + sliceIndex], + args[2 + sliceIndex], + args[3 + sliceIndex], + args[4 + sliceIndex] + ); default: return func.apply(context, Array.prototype.slice.call(args, sliceIndex)); } @@ -202,7 +220,7 @@ utils.applyArgs = function (func, context, args, sliceIndex) { * when it is called. * @return {[type]} [description] */ -utils.nextTick = function (cb) { +utils.nextTick = function(cb) { // bind the function and schedule it process.nextTick(_.bindKey(utils, 'applyArgs', cb, null, arguments, 1)); }; @@ -221,7 +239,7 @@ utils.nextTick = function (cb) { * @param {Function} func - The method that is being defined * @return {Function} */ -utils.handler = function (func) { +utils.handler = function(func) { func._provideBound = true; return func; }; @@ -242,7 +260,7 @@ utils.handler = function (func) { * * @param {Object} obj - The object to bind the methods to */ -utils.makeBoundMethods = function (obj) { +utils.makeBoundMethods = function(obj) { obj.bound = {}; for (var prop in obj) { // dearest maintainer, we want to look through the prototype @@ -258,7 +276,7 @@ utils.makeBoundMethods = function (obj) { * @param {Object} opts - a map of the options * @return {Function|undefined} - If a valid option was specified, then the constructor is returned */ -utils.funcEnum = function (config, name, opts, def) { +utils.funcEnum = function(config, name, opts, def) { var val = config[name]; switch (typeof val) { case 'undefined': @@ -296,7 +314,7 @@ utils.funcEnum = function (config, name, opts, def) { * @param {Function} transform - A function called for each element of the resulting array * @return {Array|false} - an array on success, or false on failure. */ -utils.createArray = function (input, transform) { +utils.createArray = function(input, transform) { transform = typeof transform === 'function' ? transform : _.identity; var output = []; var item; @@ -325,7 +343,7 @@ utils.createArray = function (input, transform) { * @param {WritableStream} stream - an instance of stream.Writable * @return {string} - the remaining test to be written to the stream */ -utils.getUnwrittenFromStream = function (stream) { +utils.getUnwrittenFromStream = function(stream) { var writeBuffer = utils.getStreamWriteBuffer(stream); if (!writeBuffer) return; @@ -333,11 +351,14 @@ utils.getUnwrittenFromStream = function (stream) { var out = ''; if (!writeBuffer.length) return out; - _.each(writeBuffer, function (writeReq) { + _.each(writeBuffer, function(writeReq) { if (writeReq.chunk) { // 0.9.12+ uses WriteReq objects with a chunk prop out += '' + writeReq.chunk; - } else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { + } else if ( + _.isArray(writeReq) && + (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0])) + ) { // 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...]. out += '' + writeReq[0]; } else { @@ -347,7 +368,7 @@ utils.getUnwrittenFromStream = function (stream) { return out; }; -utils.getStreamWriteBuffer = function (stream) { +utils.getStreamWriteBuffer = function(stream) { if (!stream || !stream._writableState) return; var writeState = stream._writableState; @@ -359,7 +380,7 @@ utils.getStreamWriteBuffer = function (stream) { } }; -utils.clearWriteStreamBuffer = function (stream) { +utils.clearWriteStreamBuffer = function(stream) { var buffer = utils.getStreamWriteBuffer(stream); return buffer && buffer.splice(0); }; @@ -367,8 +388,8 @@ utils.clearWriteStreamBuffer = function (stream) { /** * return the current time in milliseconds since epoch */ -utils.now = function () { - return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime(); +utils.now = function() { + return typeof Date.now === 'function' ? Date.now() : new Date().getTime(); }; module.exports = utils; diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index 51ec4781b..8de7c810c 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -3,43 +3,55 @@ var Client = require('../../src/elasticsearch').Client; var _ = require('lodash'); var times = require('async').times; -process.once('message', function (port) { +process.once('message', function(port) { var es = new Client({ host: 'http://127.0.0.1:' + port, - log: false + log: false, }); - times(1000, function (n, done) { - es.search({ - body: { - query: { - match_all: {} - } + times( + 1000, + function(n, done) { + es.search( + { + body: { + query: { + match_all: {}, + }, + }, + }, + done + ); + clock.tick(10); + }, + function(err) { + var conns = es.transport.connectionPool._conns; + var sockets = _([].concat(conns.dead, conns.alive)) + .transform(function(sockets, conn) { + sockets.push( + _.values(conn.agent.sockets), + _.values(conn.agent.freeSockets) + ); + }, []) + .flattenDeep() + .value(); + + es.close(); + + var out = { + socketCount: err || sockets.length, + remaining: + _.filter(sockets, { destroyed: true }).length - sockets.length, + timeouts: + _.size(clock.timers) && _.map(clock.timers, 'func').map(String), + }; + + clock.restore(); + if (process.connected) { + process.send(out); + } else { + console.log(out); } - }, done); - clock.tick(10); - }, function (err) { - var conns = es.transport.connectionPool._conns; - var sockets = _([].concat(conns.dead, conns.alive)) - .transform(function (sockets, conn) { - sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets)); - }, []) - .flattenDeep() - .value(); - - es.close(); - - var out = { - socketCount: err || sockets.length, - remaining: _.filter(sockets, { destroyed: true }).length - sockets.length, - timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String) - }; - - clock.restore(); - if (process.connected) { - process.send(out) - } else { - console.log(out); } - }); + ); }); diff --git a/test/fixtures/keepalive_server.js b/test/fixtures/keepalive_server.js index 11d250b11..0a52b9083 100644 --- a/test/fixtures/keepalive_server.js +++ b/test/fixtures/keepalive_server.js @@ -5,15 +5,15 @@ // timeouts aren't being left behind var express = require('express'); -var app = express().post('/_search', function (req, res) { +var app = express().post('/_search', function(req, res) { res.json(200, { hits: { hits: [] } }); }); var server = require('http').createServer(app); -server.listen(function () { +server.listen(function() { var port = server.address().port; if (process.connected) { - process.send(port) + process.send(port); } else { console.log(port); } diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index 0a7c1869c..813fe8767 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -21,37 +21,52 @@ var client = null; module.exports = { create: function create(apiVersion, port, host, cb) { // create a client and ping the server for up to 15 seconds - doCreateClient({ - logConfig: null - }, function () { - var attemptsRemaining = 60; - var timeout = 500; + doCreateClient( + { + logConfig: null, + }, + function() { + var attemptsRemaining = 60; + var timeout = 500; - (function ping() { - client.info({ - maxRetries: 0, - requestTimeout: 100 - }, function (err, resp) { - if (err && --attemptsRemaining) { - setTimeout(ping, timeout); - } else if (err) { - cb(new Error('unable to establish contact with ES at ' + JSON.stringify({ - host: host, - port: port, - err: err - }))); - } else if (resp.name !== 'elasticsearch_js_test_runner') { - console.log(resp); - cb(new Error('Almosted wiped out another es node. Shut-down all instances of ES and try again.')); - } else { - // create a new client - doCreateClient(function () { - cb(void 0, client); - }); - } - }); - }()); - }); + (function ping() { + client.info( + { + maxRetries: 0, + requestTimeout: 100, + }, + function(err, resp) { + if (err && --attemptsRemaining) { + setTimeout(ping, timeout); + } else if (err) { + cb( + new Error( + 'unable to establish contact with ES at ' + + JSON.stringify({ + host: host, + port: port, + err: err, + }) + ) + ); + } else if (resp.name !== 'elasticsearch_js_test_runner') { + console.log(resp); + cb( + new Error( + 'Almosted wiped out another es node. Shut-down all instances of ES and try again.' + ) + ); + } else { + // create a new client + doCreateClient(function() { + cb(void 0, client); + }); + } + } + ); + })(); + } + ); function doCreateClient(options, cb) { if (typeof options === 'function') { @@ -90,50 +105,61 @@ module.exports = { hosts: [ { host: host, - port: port - } + port: port, + }, ], log: logConfig, - defer: function () { + defer: function() { return Bluebird.defer(); - } + }, }); - client.clearEs = function () { + client.clearEs = function() { return Bluebird.all([ client.indices.delete({ index: '*', ignore: 404 }), client.indices.deleteTemplate({ name: '*', ignore: 404 }), - client.snapshot.getRepository() - .then(_.keys) - .map(function (repo) { - return client.snapshot.get({ - repository: repo, - snapshot: '_all' - }) - .then(function (resp) { - return _.map(resp.snapshots, 'snapshot'); - }, function () { - return []; - }) - .map(function (snapshot) { - return client.snapshot.delete({ - repository: repo, - snapshot: snapshot - }); - }, { concurrency: 1 }) - .then(function () { - return client.snapshot.deleteRepository({ - repository: repo - }); - }); - }, { concurrency: 1 }) + client.snapshot + .getRepository() + .then(_.keys) + .map( + function(repo) { + return client.snapshot + .get({ + repository: repo, + snapshot: '_all', + }) + .then( + function(resp) { + return _.map(resp.snapshots, 'snapshot'); + }, + function() { + return []; + } + ) + .map( + function(snapshot) { + return client.snapshot.delete({ + repository: repo, + snapshot: snapshot, + }); + }, + { concurrency: 1 } + ) + .then(function() { + return client.snapshot.deleteRepository({ + repository: repo, + }); + }); + }, + { concurrency: 1 } + ), ]); }; process.nextTick(cb); } }, - get: function () { + get: function() { return client; - } + }, }; diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index 518cfa039..440802bdc 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -1,8 +1,10 @@ -module.exports = function (branch) { +module.exports = function(branch) { var path = require('path'); var YamlFile = require('./yaml_file'); var root = require('find-root')(__dirname); - var rootReq = function (loc) { return require(path.join(root, loc)); }; + var rootReq = function(loc) { + return require(path.join(root, loc)); + }; var _ = require('lodash'); var utils = rootReq('src/lib/utils'); var clientManager = require('./client_manager'); @@ -16,23 +18,25 @@ module.exports = function (branch) { console.log(' port:', port); console.log(' api version:', apiVersion); - describe('integration', function () { + describe('integration', function() { this.timeout(30000); // before running any tests... - before(function (done) { + before(function(done) { this.timeout(5 * 60 * 1000); clientManager.create(apiVersion, port, host, done); }); - before(function () { + before(function() { // make sure ES is empty return clientManager.get().clearEs(); }); - _.map(require('./yaml_tests_' + utils.snakeCase(branch) + '.json'), function (docs, filename) { - return new YamlFile(filename, docs); - }); - + _.map( + require('./yaml_tests_' + utils.snakeCase(branch) + '.json'), + function(docs, filename) { + return new YamlFile(filename, docs); + } + ); }); }; diff --git a/test/integration/yaml_suite/yaml_doc.js b/test/integration/yaml_suite/yaml_doc.js index cd7911536..2fefd4e2d 100644 --- a/test/integration/yaml_suite/yaml_doc.js +++ b/test/integration/yaml_suite/yaml_doc.js @@ -14,7 +14,13 @@ var expect = require('expect.js'); var clientManager = require('./client_manager'); var inspect = require('util').inspect; -var implementedFeatures = ['gtelte', 'regex', 'benchmark', 'stash_in_path', 'groovy_scripting']; +var 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 @@ -41,14 +47,16 @@ var versionRE = new RegExp('^(?:' + versionExp + ')$'); * Regular Expression to extract a version range from a string * @type {RegExp} */ -var versionRangeRE = new RegExp('^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$'); +var versionRangeRE = new RegExp( + '^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$' +); /** * Fetches the client.info, and parses out the version number to a comparable string * @param done {Function} - callback */ function getVersionFromES(done) { - clientManager.get().info({}, function (err, resp) { + clientManager.get().info({}, function(err, resp) { if (err) { throw new Error('unable to get info about ES'); } @@ -70,9 +78,9 @@ function versionToComparableString(version, def) { return def; } - var parts = _.map(version.split('.'), function (part) { + var parts = _.map(version.split('.'), function(part) { part = '' + _.parseInt(part); - return (new Array(Math.max(4 - part.length, 0))).join('0') + part; + return new Array(Math.max(4 - part.length, 0)).join('0') + part; }); while (parts.length < 3) { @@ -95,7 +103,7 @@ function rangeMatchesCurrentVersion(rangeString, done) { } if (!ES_VERSION) { - getVersionFromES(function () { + getVersionFromES(function() { rangeMatchesCurrentVersion(rangeString, done); }); return; @@ -104,7 +112,6 @@ function rangeMatchesCurrentVersion(rangeString, done) { done(YamlDoc.compareRangeToVersion(rangeString, ES_VERSION)); } - function YamlDoc(doc, file) { var self = this; @@ -114,66 +121,71 @@ function YamlDoc(doc, file) { self._last_requests_response = null; // 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]; + self._actions = _.map( + self.flattenTestActions(doc[self.description]), + function(action) { + // get the method that will do the action + var method = self['do_' + action.name]; - // check that it's a function - expect(method || 'YamlDoc#' + action.name).to.be.a('function'); + // check that it's a function + expect(method || 'YamlDoc#' + action.name).to.be.a('function'); - if (_.isPlainObject(action.args)) { - action.name += '(' + JSON.stringify(action.args) + ')'; - } else if (action.args) { - action.name += '(' + action.args + ')'; - } - - // wrap in a check for skipping - action.bound = _.bind(method, self, action.args); - - // create a function that can be passed to mocha or async - action.testable = function (_cb) { - function done(err) { - process.nextTick(function () { - if (err) { - err.message += ' in ' + action.name; - } - _cb(err); - }); + if (_.isPlainObject(action.args)) { + action.name += '(' + JSON.stringify(action.args) + ')'; + } else if (action.args) { + action.name += '(' + action.args + ')'; } - if (self.skipping || self.file.skipping) { - return done(); - } - if (method.length > 1) { - action.bound(done); - } else { - try { - action.bound(); - process.nextTick(done); - } catch (err) { - done(err); + // wrap in a check for skipping + action.bound = _.bind(method, self, action.args); + + // create a function that can be passed to mocha or async + action.testable = function(_cb) { + function done(err) { + process.nextTick(function() { + if (err) { + err.message += ' in ' + action.name; + } + _cb(err); + }); } - } - }; - return action; - }); + if (self.skipping || self.file.skipping) { + return done(); + } + if (method.length > 1) { + action.bound(done); + } else { + try { + action.bound(); + process.nextTick(done); + } catch (err) { + done(err); + } + } + }; - self.getActionsRunners = function () { - return self._actions.map(function (action) { - return function (cb) { - clientManager.get().transport.log.debug( - '===========================\n' + - action.name + - '\n===========================' - ); + return action; + } + ); + + self.getActionsRunners = function() { + return self._actions.map(function(action) { + return function(cb) { + clientManager + .get() + .transport.log.debug( + '===========================\n' + + action.name + + '\n===========================' + ); return action.testable(cb); }; }); }; } -YamlDoc.compareRangeToVersion = function (range, version) { +YamlDoc.compareRangeToVersion = function(range, version) { expect(range).to.match(versionRangeRE); var rangeMatch = versionRangeRE.exec(range); @@ -184,11 +196,12 @@ YamlDoc.compareRangeToVersion = function (range, version) { var max = versionToComparableString(rangeMatch[2], Infinity); var comp = versionToComparableString(versionMatch[1], Infinity); - return (min === -Infinity || min <= comp) && (max === Infinity || max >= comp); + return ( + (min === -Infinity || min <= comp) && (max === Infinity || max >= comp) + ); }; YamlDoc.prototype = { - /** * convert tests actions * from: [ {name:args, name:args}, {name:args}, ... ] @@ -196,20 +209,24 @@ YamlDoc.prototype = { * so it's easier to work with * @param {ArrayOfObjects} config - Actions to be taken as defined in the yaml specs */ - flattenTestActions: function (config) { + flattenTestActions: function(config) { // creates [ [ {name:"", args:"" }, ... ], ... ] // from [ {name:args, name:args}, {name:args} ] - var actionSets = _.map(config, function (set) { - return _.map(_.toPairs(set), function (pair) { + var actionSets = _.map(config, function(set) { + return _.map(_.toPairs(set), function(pair) { return { name: pair[0], args: pair[1] }; }); }); // do a single level flatten, merge=ing the nested arrays from step one // into a master array, creating an array of action objects - return _.reduce(actionSets, function (note, set) { - return note.concat(set); - }, []); + return _.reduce( + actionSets, + function(note, set) { + return note.concat(set); + }, + [] + ); }, /** @@ -218,7 +235,7 @@ YamlDoc.prototype = { * @param {Function} ittr - The function to call for each action. * @return {undefined} */ - each: function (ittr) { + each: function(ittr) { for (var i = 0; i < this._actions.length; i++) { if (ittr(this._actions[i].testable, this._actions[i].name) === false) { break; @@ -248,16 +265,17 @@ YamlDoc.prototype = { * @param {string} path - The dot-notation path to the value needed. * @return {*} - The value requested, or undefined if it was not found */ - get: function (path, from) { + get: function(path, from) { var self = this; - var log = process.env.LOG_GETS && !from ? console.log.bind(console) : function () {}; + var log = + process.env.LOG_GETS && !from ? console.log.bind(console) : function() {}; var i; if (path === '$body') { // shortcut, the test just wants the whole body return self._last_requests_response; } else if (path) { - path = path.replace(/\.\$([a-zA-Z0-9_]+)/g, function (m, name) { + path = path.replace(/\.\$([a-zA-Z0-9_]+)/g, function(m, name) { return '.' + self._stash[name]; }); } @@ -273,14 +291,20 @@ YamlDoc.prototype = { log('getting', path, 'from', from); - var steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) { - return step.replace(/\uffff/g, '.'); - }); + var steps = _.map( + path ? path.replace(/\\\./g, '\uffff').split('.') : [], + function(step) { + return step.replace(/\uffff/g, '.'); + } + ); var remainingSteps; for (i = 0; from != null && i < steps.length; i++) { if (from[steps[i]] === void 0) { - remainingSteps = steps.slice(i).join('.').replace(/\\\./g, '.'); + remainingSteps = steps + .slice(i) + .join('.') + .replace(/\\\./g, '.'); from = from[remainingSteps]; break; } else { @@ -299,36 +323,49 @@ YamlDoc.prototype = { * @param args * @param done */ - do_skip: function (args, done) { + do_skip: function(args, done) { if (args.version) { - return rangeMatchesCurrentVersion(args.version, _.bind(function (match) { - if (match) { - if (this.description === 'setup') { - this.file.skipping = true; - // console.log('skipping this file' + (args.reason ? ' because ' + args.reason : '')); + return rangeMatchesCurrentVersion( + args.version, + _.bind(function(match) { + if (match) { + if (this.description === 'setup') { + this.file.skipping = true; + // console.log('skipping this file' + (args.reason ? ' because ' + args.reason : '')); + } else { + this.skipping = true; + // console.log('skipping the rest of this doc' + (args.reason ? ' because ' + args.reason : '')); + } } else { - this.skipping = true; - // console.log('skipping the rest of this doc' + (args.reason ? ' because ' + args.reason : '')); + this.skipping = false; + this.file.skipping = false; } - } else { - this.skipping = false; - this.file.skipping = false; - } - done(); - }, this)); + done(); + }, this) + ); } if (args.features) { - var features = Array.isArray(args.features) ? args.features : [args.features]; + var features = Array.isArray(args.features) + ? args.features + : [args.features]; var notImplemented = _.difference(features, implementedFeatures); if (notImplemented.length) { if (this.description === 'setup') { this.file.skipping = true; - console.log('skipping this file because ' + notImplemented.join(' & ') + ' are not implemented'); + console.log( + 'skipping this file because ' + + notImplemented.join(' & ') + + ' are not implemented' + ); } else { this.skipping = true; - console.log('skipping the rest of this doc because ' + notImplemented.join(' & ') + ' are not implemented'); + console.log( + 'skipping the rest of this doc because ' + + notImplemented.join(' & ') + + ' are not implemented' + ); } } return done(); @@ -342,12 +379,12 @@ YamlDoc.prototype = { * @param {Function} done [description] * @return {[type]} [description] */ - do_do: function (args, done) { + do_do: function(args, done) { var catcher; if (process.env.LOG_DO) { var __done = done; - done = function (err, resp) { + done = function(err, resp) { console.log('doing', clientActionName, 'with', params); console.log('got', resp); __done(err, resp); @@ -399,7 +436,11 @@ YamlDoc.prototype = { var otherKeys = _.keys(args); var action = otherKeys.shift(); if (otherKeys.length) { - return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', '))); + return done( + new TypeError( + 'Unexpected top-level args to "do": ' + otherKeys.join(', ') + ) + ); } var client = clientManager.get(); @@ -407,38 +448,47 @@ YamlDoc.prototype = { var clientAction = this.get(clientActionName, client); _.assign(inputParams, args[action]); - var params = _.transform(inputParams, _.bind(function (params, val, name) { - var camelName = _.camelCase(name); + var params = _.transform( + inputParams, + _.bind(function(params, val, name) { + var 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) { - if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) { - return true; - } - }); + // 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) { + if ( + (url.opt && url.opt[camelName]) || + (url.req && url.req[camelName]) + ) { + return true; + } + }); - // if we do know this param name, use the camelCase verison - if (knownParam || knownUrlParam) { - paramName = camelName; - } - - // for ercursively traversing the params to replace '$stashed' vars - var transformObject = function (vals, val, i) { - if (_.isString(val)) { - val = (val[0] === '$') ? this.get(val) : val; - } else if (_.isPlainObject(val) || _.isArray(val)) { - val = _.transform(val, transformObject); + // if we do know this param name, use the camelCase verison + if (knownParam || knownUrlParam) { + paramName = camelName; } - vals[i] = val; - }.bind(this); + // for ercursively traversing the params to replace '$stashed' vars + var transformObject = function(vals, val, i) { + if (_.isString(val)) { + val = val[0] === '$' ? this.get(val) : val; + } else if (_.isPlainObject(val) || _.isArray(val)) { + val = _.transform(val, transformObject); + } - transformObject(params, val, paramName); - }, this), {}); + vals[i] = val; + }.bind(this); + transformObject(params, val, paramName); + }, this), + {} + ); expect(clientAction || clientActionName).to.be.a('function'); @@ -448,7 +498,7 @@ YamlDoc.prototype = { } var timeoutId; - var cb = _.bind(function (error, body) { + var cb = _.bind(function(error, body) { this._last_requests_response = body; clearTimeout(timeoutId); @@ -474,13 +524,16 @@ YamlDoc.prototype = { }, this); var 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(); - this.skipping = true; - this._last_requests_response = {}; - done(); - }.bind(this), 20000); + timeoutId = setTimeout( + function() { + // request timed out, so we will skip the rest of the tests and continue + req.abort(); + this.skipping = true; + this._last_requests_response = {}; + done(); + }.bind(this), + 20000 + ); }, /** @@ -493,10 +546,13 @@ YamlDoc.prototype = { * @param {Object} args - The object set to the "set" key in the test * @return {undefined} */ - do_set: function (args) { - _.forOwn(args, _.bind(function (name, path) { - this._stash[name] = this.get(path); - }, this)); + do_set: function(args) { + _.forOwn( + args, + _.bind(function(name, path) { + this._stash[name] = this.get(path); + }, this) + ); }, /** @@ -506,7 +562,7 @@ YamlDoc.prototype = { * @param {string} path - Path to the response value to test * @return {undefined} */ - do_is_true: function (path) { + do_is_true: function(path) { var val = this.get(path); try { expect(Boolean(val)).to.be(true, 'path: ' + path); @@ -522,12 +578,14 @@ YamlDoc.prototype = { * @param {string} path - Path to the response value to test * @return {undefined} */ - do_is_false: function (path) { + do_is_false: function(path) { var val = this.get(path); try { expect(Boolean(val)).to.be(false, 'path: ' + path); } catch (e) { - throw new Error('expected path "' + path + '" to be false but got ' + val); + throw new Error( + 'expected path "' + path + '" to be false but got ' + val + ); } }, @@ -562,7 +620,7 @@ YamlDoc.prototype = { * * @return {undefined} */ - do_match: function (args) { + do_match: function(args) { var self = this; // recursively replace all $var within args @@ -572,80 +630,77 @@ YamlDoc.prototype = { } if (_.isString(val)) { - lvl[key] = val.replace(/\$[a-zA-Z0-9_]+/g, function (name) { + lvl[key] = val.replace(/\$[a-zA-Z0-9_]+/g, function(name) { return self.get(name); }); } }); - _.forOwn(args, _.bind(function (match, path) { - var origMatch = match; + _.forOwn( + args, + _.bind(function(match, path) { + var origMatch = match; - var maybeRE = false; - var usedRE = false; + var maybeRE = false; + var usedRE = false; - if (_.isString(match)) { - // convert the matcher into a compatible string for building a regexp - maybeRE = match - // replace comments, but allow the # to be escaped like \# - .replace(reCommentsRE, function (match, prevChar) { - if (prevChar === '\\') { - return match; - } else { - return prevChar + '\n'; - } - }) - // remove all whitespace from the expression, all meaningful - // whitespace is represented with \s - .replace(reWhitespaceRE, ''); + if (_.isString(match)) { + // convert the matcher into a compatible string for building a regexp + maybeRE = match + // replace comments, but allow the # to be escaped like \# + .replace(reCommentsRE, function(match, prevChar) { + if (prevChar === '\\') { + return match; + } else { + return prevChar + '\n'; + } + }) + // remove all whitespace from the expression, all meaningful + // whitespace is represented with \s + .replace(reWhitespaceRE, ''); - var startsWithSlash = maybeRE[0] === '/'; - var endsWithSlash = maybeRE[maybeRE.length - 1] === '/'; + var startsWithSlash = maybeRE[0] === '/'; + var endsWithSlash = maybeRE[maybeRE.length - 1] === '/'; - if (startsWithSlash && endsWithSlash) { - usedRE = true; - match = new RegExp(maybeRE.substr(1, maybeRE.length - 2)); - } - } - - var val = this.get(path); - var test = 'eql'; - - if (match instanceof RegExp) { - test = 'match'; - - // convert falsy values to an empty string so that regexp doesn't - // cast them to the strings "false", "undefined", etc. - val = val || ''; - } - - try { - expect(val).to[test](match); - } catch (e) { - var msg = [ - '\nUnable to match', - inspect(match), - 'with the path', - inspect(path), - 'and value', - inspect(val) - ]; - - if (usedRE) { - msg.push( - 'and original matcher', - '|' + origMatch - ); + if (startsWithSlash && endsWithSlash) { + usedRE = true; + match = new RegExp(maybeRE.substr(1, maybeRE.length - 2)); + } } - msg.push( - 'original error', - e.message - ); + var val = this.get(path); + var test = 'eql'; - throw new Error(msg.join('\n')); - } - }, this)); + if (match instanceof RegExp) { + test = 'match'; + + // convert falsy values to an empty string so that regexp doesn't + // cast them to the strings "false", "undefined", etc. + val = val || ''; + } + + try { + expect(val).to[test](match); + } catch (e) { + var msg = [ + '\nUnable to match', + inspect(match), + 'with the path', + inspect(path), + 'and value', + inspect(val), + ]; + + if (usedRE) { + msg.push('and original matcher', '|' + origMatch); + } + + msg.push('original error', e.message); + + throw new Error(msg.join('\n')); + } + }, this) + ); }, /** @@ -654,10 +709,13 @@ YamlDoc.prototype = { * @param {Object} args - Hash of fields->values that need to be checked * @return {undefined} */ - do_lt: function (args) { - _.forOwn(args, _.bind(function (num, path) { - expect(this.get(path)).to.be.below(num, 'path: ' + path); - }, this)); + do_lt: function(args) { + _.forOwn( + args, + _.bind(function(num, path) { + expect(this.get(path)).to.be.below(num, 'path: ' + path); + }, this) + ); }, /** @@ -666,10 +724,13 @@ YamlDoc.prototype = { * @param {Object} args - Hash of fields->values that need to be checked * @return {undefined} */ - do_lte: function (args) { - _.forOwn(args, _.bind(function (num, path) { - expect(this.get(path) <= num).to.be.ok('path: ' + path); - }, this)); + do_lte: function(args) { + _.forOwn( + args, + _.bind(function(num, path) { + expect(this.get(path) <= num).to.be.ok('path: ' + path); + }, this) + ); }, /** @@ -678,10 +739,13 @@ YamlDoc.prototype = { * @param {Object} args - Hash of fields->values that need to be checked * @return {undefined} */ - do_gt: function (args) { - _.forOwn(args, _.bind(function (num, path) { - expect(this.get(path)).to.be.above(num, 'path: ' + path); - }, this)); + do_gt: function(args) { + _.forOwn( + args, + _.bind(function(num, path) { + expect(this.get(path)).to.be.above(num, 'path: ' + path); + }, this) + ); }, /** @@ -690,10 +754,13 @@ YamlDoc.prototype = { * @param {Object} args - Hash of fields->values that need to be checked * @return {undefined} */ - do_gte: function (args) { - _.forOwn(args, _.bind(function (num, path) { - expect(this.get(path) >= num).to.be.ok('path: ' + path); - }, this)); + do_gte: function(args) { + _.forOwn( + args, + _.bind(function(num, path) { + expect(this.get(path) >= num).to.be.ok('path: ' + path); + }, this) + ); }, /** @@ -703,9 +770,12 @@ YamlDoc.prototype = { * @param {Object} args - Hash of fields->values that need to be checked * @return {undefined} */ - do_length: function (args) { - _.forOwn(args, _.bind(function (len, path) { - expect(_.size(this.get(path))).to.eql(len, 'path: ' + path); - }, this)); - } + do_length: function(args) { + _.forOwn( + args, + _.bind(function(len, path) { + expect(_.size(this.get(path))).to.eql(len, 'path: ' + path); + }, this) + ); + }, }; diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index db776c463..b26f2cd48 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -17,28 +17,33 @@ function YamlFile(filename, docs) { // file level skipping flag file.skipping = false; - describe(filename, function () { - file.docs = _.map(docs, function (doc) { + describe(filename, function() { + file.docs = _.map(docs, function(doc) { doc = new YamlDoc(doc, file); if (doc.description === 'setup') { - beforeEach(/* doc */function (done) { - async.series(doc.getActionsRunners(), done); - }); + beforeEach( + /* doc */ function(done) { + async.series(doc.getActionsRunners(), done); + } + ); } else { - it(doc.description, function (done) { + it(doc.description, function(done) { async.series(doc.getActionsRunners(), done); }); } }); - afterEach(/* doc */function () { - clientManager.get().transport.log.debug( - '===========================\n' + - 'Cleanup\n' + - '===========================' - ); - return clientManager.get().clearEs(); - }); + afterEach( + /* doc */ function() { + clientManager + .get() + .transport.log.debug( + '===========================\n' + + 'Cleanup\n' + + '===========================' + ); + return clientManager.get().clearEs(); + } + ); }); - } diff --git a/test/mocks/browser_server.js b/test/mocks/browser_server.js index 3d0010519..ba4a94a32 100644 --- a/test/mocks/browser_server.js +++ b/test/mocks/browser_server.js @@ -5,11 +5,11 @@ var XhrServer = MockHttpRequest.MockHttpServer; var parseUrl = MockHttpRequest.prototype.parseUri; var _ = require('lodash'); -var server = new XhrServer(function (request) { +var server = new XhrServer(function(request) { var reqDetails = { method: request.method, host: request.urlParts.host, - path: request.urlParts.relative + path: request.urlParts.relative, }; var response = _.find(interceptors, reqDetails); @@ -24,36 +24,38 @@ var server = new XhrServer(function (request) { request.receive(response.status, response.body || void 0); } else { - throw new Error('No known match for request: ' + JSON.stringify(reqDetails)); + throw new Error( + 'No known match for request: ' + JSON.stringify(reqDetails) + ); } }); server.start(); -var mockNock = module.exports = function (url) { +var mockNock = (module.exports = function(url) { var parsedUrl = parseUrl(url); var req = { method: 'GET', host: parsedUrl.host, - times: 1 + times: 1, }; var modifyReq = { - get: function (path) { + get: function(path) { req.path = path; req.method = 'GET'; return modifyReq; }, - port: function (path) { + port: function(path) { req.path = path; req.method = 'POST'; return modifyReq; }, - times: function (times) { + times: function(times) { req.times = times; return modifyReq; }, - reply: function (status, body) { + reply: function(status, body) { req.status = status; req.body = body; switch (typeof req.body) { @@ -64,20 +66,22 @@ var mockNock = module.exports = function (url) { try { req.body = req.body && JSON.stringify(req.body); } catch (e) { - req.body = req.body; + // noop } } interceptors.push(req); return mockNock(url); }, - done: mockNock.done + done: mockNock.done, }; return modifyReq; -}; +}); -mockNock.done = function () { +mockNock.done = function() { if (interceptors.length) { - throw new Error('Some interceptors were not called: ' + JSON.stringify(interceptors)); + throw new Error( + 'Some interceptors were not called: ' + JSON.stringify(interceptors) + ); } }; diff --git a/test/mocks/incomming_message.js b/test/mocks/incomming_message.js index ce29326cd..d212c6830 100644 --- a/test/mocks/incomming_message.js +++ b/test/mocks/incomming_message.js @@ -19,7 +19,7 @@ function MockIncommingMessage() { this.setEncoding = sinon.stub(); this.headers = {}; - this._read = function () {}; + this._read = function() {}; } util.inherits(MockIncommingMessage, Readable); diff --git a/test/mocks/writable_stream.js b/test/mocks/writable_stream.js index 0fe6faf98..3378b98b1 100644 --- a/test/mocks/writable_stream.js +++ b/test/mocks/writable_stream.js @@ -7,32 +7,31 @@ var util = require('util'); var MockWritableStream; // defined simply for 0.10+, in detail for older versions var Writable = require('stream').Writable; - if (Writable) { // nice and simple for streams 2 - MockWritableStream = module.exports = function (opts) { + MockWritableStream = module.exports = function(opts) { Writable.call(this, opts); - this._write = function () {}; + this._write = function() {}; }; util.inherits(MockWritableStream, Writable); } else { // Node < 0.10 did not provide a usefull stream abstract var Stream = require('stream').Stream; - module.exports = MockWritableStream = function () { + module.exports = MockWritableStream = function() { Stream.call(this); this.writable = true; }; util.inherits(MockWritableStream, Stream); - MockWritableStream.prototype.write = function () { + MockWritableStream.prototype.write = function() { if (!this.writable) { this.emit('error', new Error('stream not writable')); return false; } var cb; - if (typeof(arguments[arguments.length - 1]) === 'function') { + if (typeof arguments[arguments.length - 1] === 'function') { cb = arguments[arguments.length - 1]; } @@ -41,7 +40,7 @@ if (Writable) { } }; - MockWritableStream.prototype.end = function (data, encoding) { + MockWritableStream.prototype.end = function(data, encoding) { if (typeof data === 'function') { // no callback support } else if (typeof encoding === 'function') { @@ -53,18 +52,20 @@ if (Writable) { this.writable = false; }; - MockWritableStream.prototype.destroy = function (cb) { + MockWritableStream.prototype.destroy = function(cb) { var self = this; if (!this.writable) { if (cb) { - process.nextTick(function () { cb(null); }); + process.nextTick(function() { + cb(null); + }); } return; } this.writable = false; - process.nextTick(function () { + process.nextTick(function() { if (cb) { cb(null); } @@ -74,5 +75,4 @@ if (Writable) { // There is no shutdown() for files. MockWritableStream.prototype.destroySoon = MockWritableStream.prototype.end; - } diff --git a/test/unit/browser_builds/angular.js b/test/unit/browser_builds/angular.js index d6aa07db0..b2f06d095 100644 --- a/test/unit/browser_builds/angular.js +++ b/test/unit/browser_builds/angular.js @@ -3,8 +3,8 @@ var _ = require('lodash'); var expect = require('expect.js'); var Promise = require('bluebird'); -describe('Angular esFactory', function () { - before(function () { +describe('Angular esFactory', function() { + before(function() { require('../../../src/elasticsearch.angular.js'); }); @@ -12,18 +12,18 @@ describe('Angular esFactory', function () { var $rootScope; function bootstrap(env) { - beforeEach(function () { + beforeEach(function() { var promiseProvider = _.noop; if (env.bluebirdPromises) { - promiseProvider = function ($provide) { - $provide.service('$q', function () { + promiseProvider = function($provide) { + $provide.service('$q', function() { return { - defer: function () { + defer: function() { return _.bindAll(Promise.defer(), ['resolve', 'reject']); }, reject: Promise.reject, when: Promise.resolve, - all: Promise.all + all: Promise.all, }; }); }; @@ -32,29 +32,31 @@ describe('Angular esFactory', function () { angular.mock.module(promiseProvider, 'elasticsearch'); }); - beforeEach(angular.mock.inject(function ($injector) { - esFactory = $injector.get('esFactory'); - $rootScope = $injector.get('$rootScope'); - })); + beforeEach( + angular.mock.inject(function($injector) { + esFactory = $injector.get('esFactory'); + $rootScope = $injector.get('$rootScope'); + }) + ); } - describe('basic', function () { + describe('basic', function() { bootstrap({ - bluebirdPromises: true + bluebirdPromises: true, }); - it('is available in the elasticsearch module', function () { + it('is available in the elasticsearch module', function() { expect(esFactory).to.be.a('function'); }); - it('has Transport and ConnectionPool properties', function () { + it('has Transport and ConnectionPool properties', function() { expect(esFactory).to.have.property('Transport'); expect(esFactory).to.have.property('ConnectionPool'); }); - it('returns a new client when it is called', function () { + it('returns a new client when it is called', function() { var client = esFactory({ - hosts: null + hosts: null, }); expect(client).to.have.keys('transport'); @@ -62,15 +64,18 @@ describe('Angular esFactory', function () { client.close(); }); - it('returns an error created by calling a method incorrectly', function () { + it('returns an error created by calling a method incorrectly', function() { var client = esFactory({ hosts: null }); - var prom = client.get().then(function () { - throw new Error('expected request to fail'); - }, function (err) { - expect(err).to.have.property('message'); - expect(err.message).to.match(/unable/i); - }); + var prom = client.get().then( + function() { + throw new Error('expected request to fail'); + }, + function(err) { + expect(err).to.have.property('message'); + expect(err.message).to.match(/unable/i); + } + ); $rootScope.$apply(); return prom; diff --git a/test/unit/browser_builds/generic.js b/test/unit/browser_builds/generic.js index 8af355ab1..9e2aecd75 100644 --- a/test/unit/browser_builds/generic.js +++ b/test/unit/browser_builds/generic.js @@ -1,16 +1,16 @@ var expect = require('expect.js'); -describe('elasticsearch namespace', function () { +describe('elasticsearch namespace', function() { var es = window.elasticsearch; - it('is defined on the window', function () { + it('is defined on the window', function() { expect(es).to.be.ok(); }); - it('has Client, ConnectionPool, Transport, and errors keys', function () { + it('has Client, ConnectionPool, Transport, and errors keys', function() { expect(es).to.have.keys('Client', 'ConnectionPool', 'Transport', 'errors'); }); - it('can create a client', function () { + it('can create a client', function() { var client = new es.Client({ hosts: null }); expect(client).to.have.keys('transport'); expect(client.transport).to.be.a(es.Transport); diff --git a/test/unit/browser_builds/jquery.js b/test/unit/browser_builds/jquery.js index 8edd6ae99..d08b5f455 100644 --- a/test/unit/browser_builds/jquery.js +++ b/test/unit/browser_builds/jquery.js @@ -1,16 +1,21 @@ /* global $ */ var expect = require('expect.js'); -describe('jQuery.es namespace', function () { - it('is defined on the global jQuery', function () { +describe('jQuery.es namespace', function() { + it('is defined on the global jQuery', function() { expect($.es).to.be.ok(); }); - it('has Client, ConnectionPool, Transport, and errors keys', function () { - expect($.es).to.have.keys('Client', 'ConnectionPool', 'Transport', 'errors'); + it('has Client, ConnectionPool, Transport, and errors keys', function() { + expect($.es).to.have.keys( + 'Client', + 'ConnectionPool', + 'Transport', + 'errors' + ); }); - it('can create a client', function () { + it('can create a client', function() { var client = new $.es.Client({ hosts: null }); expect(client).to.have.keys('transport'); expect(client.transport).to.be.a($.es.Transport); diff --git a/test/unit/buffer_flush_tests.js b/test/unit/buffer_flush_tests.js index 1149b415b..3a5997ea7 100644 --- a/test/unit/buffer_flush_tests.js +++ b/test/unit/buffer_flush_tests.js @@ -1,17 +1,18 @@ -module.exports = function (makeLogger) { +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'); - describe('buffer flush', 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'; + it('writes everything in the buffer to console.error', function() { + var line = + 'This string is written 10 times to create buffered output\n'; var exitHandler; - stub(process, 'once', function (event, handler) { + stub(process, 'once', function(event, handler) { if (event === 'exit') { exitHandler = handler; } @@ -21,13 +22,13 @@ module.exports = function (makeLogger) { var logger = makeLogger(); // write the line 10 times - _.times(10, function () { + _.times(10, function() { logger.onDebug(line); }); // collect everything that is written to fs.appendFileSync var flushedOutput = ''; - stub(fs, 'appendFileSync', function (path, str) { + stub(fs, 'appendFileSync', function(path, str) { flushedOutput += str; }); @@ -36,12 +37,15 @@ module.exports = function (makeLogger) { // the first line is sent immediately to _write and there is nothing we can do about that expect(flushedOutput).to.match(new RegExp(line)); - expect(flushedOutput.match(new RegExp(line, 'g'))).to.have.property('length', 9); + expect(flushedOutput.match(new RegExp(line, 'g'))).to.have.property( + 'length', + 9 + ); }); } else { - it('does not fall apart with non streams2 streams', function () { + it('does not fall apart with non streams2 streams', function() { var exitHandler; - stub(process, 'once', function (event, handler) { + stub(process, 'once', function(event, handler) { if (event === 'exit') { exitHandler = handler; } @@ -50,7 +54,7 @@ module.exports = function (makeLogger) { makeLogger(); - expect(function () { + expect(function() { // call the event handler exitHandler.call(process); }).to.not.throwError(); diff --git a/test/unit/coverage.js b/test/unit/coverage.js index c64cbd6bf..11857bde2 100644 --- a/test/unit/coverage.js +++ b/test/unit/coverage.js @@ -1,5 +1,5 @@ require('blanket')({ - pattern: require('path').join(__dirname, '../../src') + pattern: require('path').join(__dirname, '../../src'), }); require('./index'); diff --git a/test/unit/generic_logger_tests.js b/test/unit/generic_logger_tests.js index 7dc2aed02..a9c72d24e 100644 --- a/test/unit/generic_logger_tests.js +++ b/test/unit/generic_logger_tests.js @@ -3,16 +3,16 @@ var Log = require('../../src/lib/log'); var now = new Date('2013-03-01T00:00:00Z'); var sinon = require('sinon'); -module.exports = function (makeLogger) { +module.exports = function(makeLogger) { var stub = require('../utils/auto_release_stub').make(); var parent = new Log(); - afterEach(function () { + afterEach(function() { parent.close(); }); - describe('Constuctor', function () { - it('calls setupListeners, passes its new levels', function () { + describe('Constuctor', function() { + it('calls setupListeners, passes its new levels', function() { var logger = makeLogger(parent); stub(logger.constructor.prototype, 'setupListeners'); parent.close(); @@ -21,21 +21,21 @@ module.exports = function (makeLogger) { expect(logger.setupListeners).to.have.property('callCount', 1); }); - it('listens for the loggers\' "closing" event', function () { + it('listens for the loggers\' "closing" event', function() { makeLogger(parent); expect(parent.listenerCount('closing')).to.eql(1); }); }); - describe('listening levels', function () { - it('calls cleanUpListeners when the listeners are being setup', function () { + describe('listening levels', function() { + it('calls cleanUpListeners when the listeners are being setup', function() { var 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 () { + it('listens to just error when log is explicitly error', function() { makeLogger(parent, 'error'); expect(parent.listenerCount('error')).to.eql(1); expect(parent.listenerCount('warning')).to.eql(0); @@ -44,7 +44,7 @@ module.exports = function (makeLogger) { expect(parent.listenerCount('trace')).to.eql(0); }); - it('listens for all the events when level is "trace"', function () { + it('listens for all the events when level is "trace"', function() { makeLogger(parent, 'trace'); expect(parent.listenerCount('error')).to.eql(1); expect(parent.listenerCount('warning')).to.eql(1); @@ -53,7 +53,7 @@ module.exports = function (makeLogger) { expect(parent.listenerCount('trace')).to.eql(1); }); - it('listens for specific events when level is an array', function () { + it('listens for specific events when level is an array', function() { makeLogger(parent, ['error', 'trace']); expect(parent.listenerCount('error')).to.eql(1); expect(parent.listenerCount('warning')).to.eql(0); @@ -62,29 +62,35 @@ module.exports = function (makeLogger) { expect(parent.listenerCount('trace')).to.eql(1); }); - it('sets the logLevel property to the new levels', function () { + it('sets the logLevel property to the new levels', function() { var logger = makeLogger(); var levels = ['error']; logger.setupListeners(levels); - expect(logger.listeningLevels).to.eql(levels).and.not.be(levels); + expect(logger.listeningLevels) + .to.eql(levels) + .and.not.be(levels); levels = ['warning', 'trace']; logger.setupListeners(levels); - expect(logger.listeningLevels).to.eql(levels).and.not.be(levels); + expect(logger.listeningLevels) + .to.eql(levels) + .and.not.be(levels); levels = ['debug', 'debug']; logger.setupListeners(levels); - expect(logger.listeningLevels).to.eql(levels).and.not.be(levels); + expect(logger.listeningLevels) + .to.eql(levels) + .and.not.be(levels); }); - it('rejects listening levels it can not listen to', function () { + it('rejects listening levels it can not listen to', function() { var logger = makeLogger(); - expect(function () { + expect(function() { logger.setupListeners(['scream']); }).to.throwError(/unable to listen/i); }); - it('emits events because something is listening', function () { + it('emits events because something is listening', function() { makeLogger(parent, 'trace'); stub(parent, 'emit'); @@ -105,42 +111,40 @@ module.exports = function (makeLogger) { }); }); - describe('#timestamp', function () { - it('returns in the right format', function () { + describe('#timestamp', function() { + it('returns in the right format', function() { stub.autoRelease(sinon.useFakeTimers(now.getTime())); var logger = makeLogger(); expect(logger.timestamp()).to.eql('2013-03-01T00:00:00Z'); }); }); - describe('#format', function () { - it('returns a single string with the message indented', function () { + describe('#format', function() { + it('returns a single string with the message indented', function() { stub.autoRelease(sinon.useFakeTimers(now.getTime())); var logger = makeLogger(); expect(logger.format('LABEL', 'MSG')).to.eql( - 'LABEL: 2013-03-01T00:00:00Z\n' + - ' MSG\n' + - '\n' + 'LABEL: 2013-03-01T00:00:00Z\n' + ' MSG\n' + '\n' ); }); - it('properly indents multi-line messages', function () { + it('properly indents multi-line messages', function() { stub.autoRelease(sinon.useFakeTimers(now.getTime())); var logger = makeLogger(); expect(logger.format('LABEL', 'MSG\nwith\nseveral lines')).to.eql( 'LABEL: 2013-03-01T00:00:00Z\n' + - ' MSG\n' + - ' with\n' + - ' several lines\n' + - '\n' + ' MSG\n' + + ' with\n' + + ' several lines\n' + + '\n' ); }); }); - describe('#onError', function () { - it('uses the Error name when it is not just "Error"', function () { + describe('#onError', function() { + it('uses the Error name when it is not just "Error"', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('TypeError'); }); @@ -148,9 +152,9 @@ module.exports = function (makeLogger) { expect(logger.write.callCount).to.eql(1); }); - it('uses "ERROR" when the error name is "Error"', function () { + it('uses "ERROR" when the error name is "Error"', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('ERROR'); }); @@ -159,19 +163,19 @@ module.exports = function (makeLogger) { }); }); - describe('#onWarning', function () { - it('uses the "WARNING" label', function () { + describe('#onWarning', function() { + it('uses the "WARNING" label', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('WARNING'); }); logger.onWarning('message'); expect(logger.write.callCount).to.eql(1); }); - it('echos the message', function () { + it('echos the message', function() { var logger = makeLogger(); - stub(logger, 'write', function (label, msg) { + stub(logger, 'write', function(label, msg) { expect(msg).to.eql('message'); }); @@ -180,19 +184,19 @@ module.exports = function (makeLogger) { }); }); - describe('#onInfo', function () { - it('uses the "INFO" label', function () { + describe('#onInfo', function() { + it('uses the "INFO" label', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('INFO'); }); logger.onInfo('message'); expect(logger.write.callCount).to.eql(1); }); - it('echos the message', function () { + it('echos the message', function() { var logger = makeLogger(); - stub(logger, 'write', function (label, msg) { + stub(logger, 'write', function(label, msg) { expect(msg).to.eql('message'); }); @@ -201,19 +205,19 @@ module.exports = function (makeLogger) { }); }); - describe('#onDebug', function () { - it('uses the "DEBUG" label', function () { + describe('#onDebug', function() { + it('uses the "DEBUG" label', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('DEBUG'); }); logger.onDebug('message'); expect(logger.write.callCount).to.eql(1); }); - it('echos the message', function () { + it('echos the message', function() { var logger = makeLogger(); - stub(logger, 'write', function (label, msg) { + stub(logger, 'write', function(label, msg) { expect(msg).to.eql('message'); }); @@ -222,13 +226,21 @@ module.exports = function (makeLogger) { }); }); - describe('#onTrace', function () { - it('uses the "TRACE" label', function () { + describe('#onTrace', function() { + it('uses the "TRACE" label', function() { var logger = makeLogger(); - stub(logger, 'write', function (label) { + stub(logger, 'write', function(label) { expect(label).to.eql('TRACE'); }); - logger.onTrace(Log.normalizeTraceArgs('GET', 'http://place/thing?me=true', '{}', '{"ok": true}', 200)); + logger.onTrace( + Log.normalizeTraceArgs( + 'GET', + 'http://place/thing?me=true', + '{}', + '{"ok": true}', + 200 + ) + ); expect(logger.write.callCount).to.eql(1); }); }); diff --git a/test/unit/index.js b/test/unit/index.js index ed696a9c4..ee09a21dd 100644 --- a/test/unit/index.js +++ b/test/unit/index.js @@ -1,6 +1,9 @@ require('bluebird').longStackTraces(); +const { resolve } = require('path'); -var specDir = __dirname + '/specs'; -require('fs').readdirSync(specDir).forEach(function (file) { - require(specDir + '/' + file); -}); +var specDir = resolve(__dirname, 'specs'); +require('fs') + .readdirSync(specDir) + .forEach(function(file) { + require(specDir + '/' + file); + }); diff --git a/test/unit/specs/abstract_logger.js b/test/unit/specs/abstract_logger.js index 16b4dda71..d10444789 100644 --- a/test/unit/specs/abstract_logger.js +++ b/test/unit/specs/abstract_logger.js @@ -1,4 +1,4 @@ -describe('Logger Abstract', function () { +describe('Logger Abstract', function() { var expect = require('expect.js'); var Log = require('../../../src/lib/log'); var LoggerAbstract = require('../../../src/lib/logger'); @@ -7,21 +7,21 @@ describe('Logger Abstract', function () { function makeLogger(parent, levels) { return new LoggerAbstract(parent || parentLog, { - levels: Log.parseLevels(levels || []) + levels: Log.parseLevels(levels || []), }); } - beforeEach(function () { + beforeEach(function() { parentLog = new Log(); }); - afterEach(function () { + afterEach(function() { parentLog.close(); }); - describe('#write', function () { - it('requires that it is overwritten', function () { - expect(function () { + describe('#write', function() { + it('requires that it is overwritten', function() { + expect(function() { var logger = makeLogger(); logger.write(); }).to.throwError(/overwritten/); @@ -29,5 +29,4 @@ describe('Logger Abstract', function () { }); require('../generic_logger_tests')(makeLogger); - }); diff --git a/test/unit/specs/client.js b/test/unit/specs/client.js index 06ca8b1ca..693111b03 100644 --- a/test/unit/specs/client.js +++ b/test/unit/specs/client.js @@ -1,58 +1,62 @@ -describe('Client instances creation', function () { +describe('Client instances creation', function() { var stream = require('stream'); var 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; - describe('', function () { - beforeEach(function () { + describe('', function() { + beforeEach(function() { client = new es.Client(); }); - afterEach(function () { + afterEach(function() { client.close(); }); - it('throws an error linking to the es module when you try to instanciate the exports', function () { + it('throws an error linking to the es module when you try to instanciate the exports', function() { var Es = es; - expect(function () { + expect(function() { var c = new Es(); - return c + 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]; + var prev = + pkg.config.supported_es_branches[ + pkg.config.supported_es_branches.indexOf(def) + 1 + ]; - it('inherits the ' + def + ' API by default', function () { + it('inherits the ' + def + ' API by default', function() { expect(client.bulk).to.be(apis[def].bulk); expect(client.nodes.stats).to.be(apis[def].nodes.prototype.stats); }); - it('inherits the ' + prev + ' API when specified', function () { + it('inherits the ' + prev + ' API when specified', function() { client.close(); client = es.Client({ - apiVersion: prev + apiVersion: prev, }); expect(client.bulk).to.be(apis[prev].bulk); - expect(client.cluster.nodeStats).to.be(apis[prev].cluster.prototype.nodeStats); + expect(client.cluster.nodeStats).to.be( + apis[prev].cluster.prototype.nodeStats + ); }); - it('closing the client causes it\'s transport to be closed', function () { + it("closing the client causes it's transport to be closed", function() { var called = false; - client.transport.close = function () { + client.transport.close = function() { called = true; }; client.close(); expect(called).to.be(true); }); - it('creates a warning level logger by default', function () { + it('creates a warning level logger by default', function() { expect(client.transport.log.listenerCount('error')).to.eql(1); expect(client.transport.log.listenerCount('warning')).to.eql(1); expect(client.transport.log.listenerCount('info')).to.eql(0); @@ -61,21 +65,19 @@ describe('Client instances creation', function () { }); }); - describe('config', function () { - it('accepts a stream type logger', function (done) { + describe('config', function() { + it('accepts a stream type logger', function(done) { function NullStream() { stream.Writable.call(this); } util.inherits(NullStream, stream.Writable); - NullStream.prototype._write = function (/* chunk, encoding, next */) { + NullStream.prototype._write = function(/* chunk, encoding, next */) { done(); }; client = new es.Client({ - log: [ - { type: 'stream', stream: new NullStream() } - ] + log: [{ type: 'stream', stream: new NullStream() }], }); client.transport.log.error(new Error()); diff --git a/test/unit/specs/client_action.js b/test/unit/specs/client_action.js index 417d86f7f..fc3a93cce 100644 --- a/test/unit/specs/client_action.js +++ b/test/unit/specs/client_action.js @@ -13,19 +13,19 @@ var Promise = require('bluebird'); function mockClient() { return { transport: { - request: function (params, cb) { + request: function(params, cb) { if (typeof cb === 'function') { - process.nextTick(function () { + process.nextTick(function() { cb(void 0, params); }); } else { return Promise.resolve(params); } }, - defer: function () { + defer: function() { return Promise.defer(); - } - } + }, + }, }; } @@ -41,7 +41,7 @@ function makeClientAction(spec) { if (!spec.urls && !spec.url) { spec.url = { - fmt: '/' + fmt: '/', }; } @@ -58,88 +58,92 @@ function makeClientActionProxy(fn, spec) { return _.bind(proxy(fn, spec || {}), mockClient()); } - -describe('Client Action runner', function () { +describe('Client Action runner', function() { var action; // used to check that params are not clobbered - var params = (function () { + var params = (function() { var _stash = {}; - afterEach(function () { _stash = {}; }); - var make = function (params) { + afterEach(function() { + _stash = {}; + }); + var make = function(params) { _stash.orig = params; _stash.copy = _.clone(params); return params; }; - make.check = function () { + make.check = function() { expect(_stash.orig).to.eql(_stash.copy); }; return make; - }()); + })(); - describe('argument juggling', function () { - it('creates an empty param set when no params are sent', function (done) { + describe('argument juggling', function() { + it('creates an empty param set when no params are sent', function(done) { action = makeClientAction(); // note: the first arg is the callback - action(function (err, params) { + action(function(err, params) { expect(params.query).to.eql({}); done(); }); }); }); - describe('clientAction::proxy', function () { - it('proxies to the passed function', function () { - var action = makeClientActionProxy(function () { + describe('clientAction::proxy', function() { + it('proxies to the passed function', function() { + var action = makeClientActionProxy(function() { throw new Error('proxy function called'); }); - expect(function () { - action({}, function () {}); + expect(function() { + action({}, function() {}); }).to.throwError('proxy function called'); }); - it('provides the proper context', function (done) { + it('provides the proper context', function(done) { var client; - var action = makeClientActionProxy(function (params, cb) { + var action = makeClientActionProxy(function(params, cb) { client = this; - process.nextTick(function () { + process.nextTick(function() { cb(void 0, params); }); }); - action({}, function () { + action({}, function() { expect(client.transport.request).to.be.a('function'); done(); }); }); - it('handles passing just the callback', function () { - var action = makeClientActionProxy(function (params, cb) { + it('handles passing just the callback', function() { + var action = makeClientActionProxy(function(params, cb) { expect(_.isObject(params)).to.be.ok(); expect(cb).to.be.a('function'); }); - action(function () {}); + action(function() {}); }); - it('supports a param transformation function', function () { - var action = makeClientActionProxy(function (params) { - expect(params).to.have.property('transformed'); - }, { - transform: function (params) { - params.transformed = true; + it('supports a param transformation function', function() { + var action = makeClientActionProxy( + function(params) { + expect(params).to.have.property('transformed'); + }, + { + transform: function(params) { + params.transformed = true; + }, } - }); + ); - action(function () {}); + action(function() {}); }); - it('returns the proxied function\'s return value', function () { + it("returns the proxied function's return value", function() { var football = {}; - var action = makeClientActionProxy(function () { + var action = makeClientActionProxy(function() { return football; }); @@ -147,170 +151,213 @@ describe('Client Action runner', function () { }); }); - describe('param casting', function () { - describe('duration', function () { - beforeEach(function () { + describe('param casting', function() { + describe('duration', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { - type: 'duration' + type: 'duration', }, two: { - type: 'duration' + type: 'duration', }, three: { - type: 'duration' + type: 'duration', }, four: { - type: 'duration' + type: 'duration', + }, + }, + }); + }); + + it('accepts a number, string, or interval', function(done) { + action( + { + one: 1500, + two: '500', + three: '15m', + }, + function(err, params) { + if (err) { + throw err; } + expect(params.query.one).to.eql(1500); + expect(params.query.two).to.eql('500'); + expect(params.query.three).to.eql('15m'); + + done(); } - }); + ); }); - it('accepts a number, string, or interval', function (done) { - action({ - one: 1500, - two: '500', - three: '15m' - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.eql(1500); - expect(params.query.two).to.eql('500'); - expect(params.query.three).to.eql('15m'); - - done(); - }); + it('rejects date values', function(done) { + action( + { + one: new Date(), + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects date values', function (done) { - action({ - one: new Date() - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects array', function(done) { + action( + { + one: ['one'], + two: [1304], + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects array', function (done) { - action({ - one: ['one'], - two: [1304] - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); - }); - - it('rejects object', function (done) { - action({ - one: { but: 'duration' } - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects object', function(done) { + action( + { + one: { but: 'duration' }, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('list', function () { - beforeEach(function () { + describe('list', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { type: 'list' }, two: { type: 'list' }, - three: { type: 'list' } - } + three: { type: 'list' }, + }, }); }); - it('accepts a string, number, or array', function (done) { - action({ - one: 'some,strings', - two: 1430, - three: ['some', 'strings'], - }, function (err, params) { - if (err) { throw err; } - expect(params.query).to.eql({ + it('accepts a string, number, or array', function(done) { + action( + { one: 'some,strings', two: 1430, - three: 'some,strings' - }); - done(); - }); - }); - - it('it rejects regexp', function (done) { - action({ - one: /regexp!/g - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); - }); - - it('it rejects objects', function (done) { - action({ - one: { - pasta: 'sauce' + three: ['some', 'strings'], + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query).to.eql({ + one: 'some,strings', + two: 1430, + three: 'some,strings', + }); + done(); } - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + ); + }); + + it('it rejects regexp', function(done) { + action( + { + one: /regexp!/g, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); + }); + + it('it rejects objects', function(done) { + action( + { + one: { + pasta: 'sauce', + }, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('enum', function () { - beforeEach(function () { + describe('enum', function() { + beforeEach(function() { action = makeClientAction({ params: { - one: { type: 'enum', options: ['opt', 'other opt', '150', 'true'] } + one: { type: 'enum', options: ['opt', 'other opt', '150', 'true'] }, + }, + }); + }); + + it('accepts any value in the list', function(done) { + action( + { + one: 'opt', + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.eql('opt'); + done(); } - }); + ); }); - it('accepts any value in the list', function (done) { - action({ - one: 'opt' - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.eql('opt'); - done(); - }); + it('accepts any value kind of in the list', function(done) { + action( + { + one: 150, + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be('150'); + done(); + } + ); }); - it('accepts any value kind of in the list', function (done) { - action({ - one: 150 - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be('150'); - done(); - }); + it('accepts string versions of booleans', function(done) { + action( + { + one: true, + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be('true'); + done(); + } + ); }); - it('accepts string versions of booleans', function (done) { - action({ - one: true - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be('true'); - done(); - }); - }); - - it('it rejects things not in the list', function (done) { - action({ - one: 'not an opt' - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('it rejects things not in the list', function(done) { + action( + { + one: 'not an opt', + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('boolean', function () { - beforeEach(function () { + describe('boolean', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { type: 'boolean' }, @@ -319,49 +366,59 @@ describe('Client Action runner', function () { four: { type: 'boolean' }, five: { type: 'boolean' }, six: { type: 'boolean' }, + }, + }); + }); + + it('casts "off", "no", and other falsey things to false', function(done) { + action( + { + one: 'off', + two: 'no', + three: false, + four: '', + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be(false); + expect(params.query.two).to.be(false); + expect(params.query.three).to.be(false); + expect(params.query.four).to.be(false); + done(); } - }); + ); }); - it('casts "off", "no", and other falsey things to false', function (done) { - action({ - one: 'off', - two: 'no', - three: false, - four: '' - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be(false); - expect(params.query.two).to.be(false); - expect(params.query.three).to.be(false); - expect(params.query.four).to.be(false); - done(); - }); - }); - - it('cast most everything else to true', function (done) { - action({ - one: 'yes', - two: 'ok', - three: true, - four: 1, - five: new Date(), - six: {} - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be(true); - expect(params.query.two).to.be(true); - expect(params.query.three).to.be(true); - expect(params.query.four).to.be(true); - expect(params.query.five).to.be(true); - expect(params.query.six).to.be(true); - done(); - }); + it('cast most everything else to true', function(done) { + action( + { + one: 'yes', + two: 'ok', + three: true, + four: 1, + five: new Date(), + six: {}, + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be(true); + expect(params.query.two).to.be(true); + expect(params.query.three).to.be(true); + expect(params.query.four).to.be(true); + expect(params.query.five).to.be(true); + expect(params.query.six).to.be(true); + done(); + } + ); }); }); - describe('number', function () { - beforeEach(function () { + describe('number', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { type: 'number' }, @@ -370,89 +427,111 @@ describe('Client Action runner', function () { four: { type: 'number' }, five: { type: 'number' }, six: { type: 'number' }, + }, + }); + }); + + it('casts integers properly', function(done) { + action( + { + one: '42', + two: '-69', + three: 15, + four: -100, + five: '0xFF', + six: 0xfff, + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be(42); + expect(params.query.two).to.be(-69); + expect(params.query.three).to.be(15); + expect(params.query.four).to.be(-100); + expect(params.query.five).to.be(255); + expect(params.query.six).to.be(4095); + done(); } - }); + ); }); - it('casts integers properly', function (done) { - action({ - one: '42', - two: '-69', - three: 15, - four: -100, - five: '0xFF', - six: 0xFFF - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be(42); - expect(params.query.two).to.be(-69); - expect(params.query.three).to.be(15); - expect(params.query.four).to.be(-100); - expect(params.query.five).to.be(255); - expect(params.query.six).to.be(4095); - done(); - }); + it('casts floats properly', function(done) { + action( + { + one: '-1.6', + two: '4.536', + three: -2.6, + four: 3.1415, + five: 8e5, + six: '123e-2', + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be(-1.6); + expect(params.query.two).to.be(4.536); + expect(params.query.three).to.be(-2.6); + expect(params.query.four).to.be(3.1415); + expect(params.query.five).to.be(800000); + expect(params.query.six).to.be(1.23); + done(); + } + ); }); - it('casts floats properly', function (done) { - action({ - one: '-1.6', - two: '4.536', - three: -2.6, - four: 3.1415, - five: 8e5, - six: '123e-2', - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be(-1.6); - expect(params.query.two).to.be(4.536); - expect(params.query.three).to.be(-2.6); - expect(params.query.four).to.be(3.1415); - expect(params.query.five).to.be(800000); - expect(params.query.six).to.be(1.23); - done(); - }); + it('rejects dates', function(done) { + action( + { + one: new Date(), + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects dates', function (done) { - action({ - one: new Date() - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects objects', function(done) { + action( + { + one: {}, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects objects', function (done) { - action({ - one: {} - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects arrays', function(done) { + action( + { + one: [], + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects arrays', function (done) { - action({ - one: [] - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); - }); - - it('rejects regexp', function (done) { - action({ - one: /pasta/g - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects regexp', function(done) { + action( + { + one: /pasta/g, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('string', function () { - beforeEach(function () { + describe('string', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { type: 'string' }, @@ -461,69 +540,86 @@ describe('Client Action runner', function () { four: { type: 'string' }, five: { type: 'string' }, six: { type: 'string' }, + }, + }); + }); + + it('accepts numbers and strings', function(done) { + action( + { + one: '42', + two: '-69', + three: 15, + four: -100, + five: '0xFF', + six: 0xfff, + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be('42'); + expect(params.query.two).to.be('-69'); + expect(params.query.three).to.be('15'); + expect(params.query.four).to.be('-100'); + expect(params.query.five).to.be('0xFF'); + expect(params.query.six).to.be('4095'); + done(); } - }); + ); }); - it('accepts numbers and strings', function (done) { - action({ - one: '42', - two: '-69', - three: 15, - four: -100, - five: '0xFF', - six: 0xFFF - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be('42'); - expect(params.query.two).to.be('-69'); - expect(params.query.three).to.be('15'); - expect(params.query.four).to.be('-100'); - expect(params.query.five).to.be('0xFF'); - expect(params.query.six).to.be('4095'); - done(); - }); + it('rejects dates', function(done) { + action( + { + one: new Date(), + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects dates', function (done) { - action({ - one: new Date() - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects objects', function(done) { + action( + { + one: {}, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects objects', function (done) { - action({ - one: {} - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects arrays', function(done) { + action( + { + one: [], + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects arrays', function (done) { - action({ - one: [] - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); - }); - - it('rejects regexp', function (done) { - action({ - one: /pasta/g - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects regexp', function(done) { + action( + { + one: /pasta/g, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('time', function () { - beforeEach(function () { + describe('time', function() { + beforeEach(function() { action = makeClientAction({ params: { one: { type: 'time' }, @@ -532,346 +628,400 @@ describe('Client Action runner', function () { four: { type: 'time' }, five: { type: 'time' }, six: { type: 'time' }, - } + }, }); }); - it('accepts numbers, strings, and dates', function (done) { + it('accepts numbers, strings, and dates', function(done) { var now = new Date(); - action({ - one: '42', - two: '-69', - three: 15, - four: now, - five: new Date('2013-03-01T01:10:00Z') - }, function (err, params) { - if (err) { throw err; } - expect(params.query.one).to.be('42'); - expect(params.query.two).to.be('-69'); - expect(params.query.three).to.be('15'); - expect(params.query.four).to.be('' + now.getTime()); - expect(params.query.five).to.be('1362100200000'); - done(); - }); + action( + { + one: '42', + two: '-69', + three: 15, + four: now, + five: new Date('2013-03-01T01:10:00Z'), + }, + function(err, params) { + if (err) { + throw err; + } + expect(params.query.one).to.be('42'); + expect(params.query.two).to.be('-69'); + expect(params.query.three).to.be('15'); + expect(params.query.four).to.be('' + now.getTime()); + expect(params.query.five).to.be('1362100200000'); + done(); + } + ); }); - it('rejects objects', function (done) { - action({ - one: {} - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects objects', function(done) { + action( + { + one: {}, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects arrays', function (done) { - action({ - one: [] - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects arrays', function(done) { + action( + { + one: [], + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); - it('rejects regexp', function (done) { - action({ - one: /pasta/g - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('rejects regexp', function(done) { + action( + { + one: /pasta/g, + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); }); - describe('passing of control params from spec', function () { - it('passes bulkBody', function (done) { + describe('passing of control params from spec', function() { + it('passes bulkBody', function(done) { var action = makeClientAction({ - bulkBody: true + bulkBody: true, }); - action({}, function (err, params) { + action({}, function(err, params) { expect(params.bulkBody).to.be(true); done(); }); }); - it('sets castExists when the method in the spec is HEAD', function (done) { + it('sets castExists when the method in the spec is HEAD', function(done) { var action = makeClientAction({ - method: 'HEAD' + method: 'HEAD', }); - action({}, function (err, params) { + action({}, function(err, params) { expect(params.castExists).to.be(true); done(); }); }); }); - describe('body handling', function () { + describe('body handling', function() { var action = makeClientAction({ - needsBody: true + needsBody: true, }); - it('passed the body when it is set', function (done) { + it('passed the body when it is set', function(done) { var body = '{"JSON":"PLEASE"}'; - action({ body: body }, function (err, params) { + action({ body: body }, function(err, params) { expect(params.body).to.be(body); done(); }); }); - it('errors when the body is not set but required', function (done) { - action().then(function () { - done(new Error('Error should have been raised')); - }, function (err) { - expect(err).to.be.a(TypeError); - done(); - }); + it('errors when the body is not set but required', function(done) { + action().then( + function() { + done(new Error('Error should have been raised')); + }, + function(err) { + expect(err).to.be.a(TypeError); + done(); + } + ); }); }); - describe('passing of http method', function () { - it('uppercases and passed the default method', function (done) { + describe('passing of http method', function() { + it('uppercases and passed the default method', function(done) { var action = makeClientAction({ - method: 'POST' + method: 'POST', }); - action({ method: 'get' }, function (err, params) { + action({ method: 'get' }, function(err, params) { expect(params.method).to.be('GET'); done(); }); }); - it('uppercases and passed the default method', function (done) { + it('uppercases and passed the default method', function(done) { var action = makeClientAction({ - method: 'POST' + method: 'POST', }); - action({}, function (err, params) { + action({}, function(err, params) { expect(params.method).to.be('POST'); done(); }); }); }); - describe('passing of ignore param', function () { - it('passes ignore as an array', function (done) { + describe('passing of ignore param', function() { + it('passes ignore as an array', function(done) { var action = makeClientAction({}); - action({ ignore: 404 }, function (err, params) { + action({ ignore: 404 }, function(err, params) { expect(params.ignore).to.eql([404]); done(); }); }); }); - describe('passing requestTimeout', function () { - it('passes passes the spec value by default', function (done) { + describe('passing requestTimeout', function() { + it('passes passes the spec value by default', function(done) { var action = makeClientAction({ - requestTimeout: 100 + requestTimeout: 100, }); - action({}, function (err, params) { + action({}, function(err, params) { expect(params.requestTimeout).to.be(100); done(); }); }); - it('passes the provided value', function (done) { + it('passes the provided value', function(done) { var action = makeClientAction({ - requestTimeout: 100 + requestTimeout: 100, }); - action({ requestTimeout: 3000 }, function (err, params) { + action({ requestTimeout: 3000 }, function(err, params) { expect(params.requestTimeout).to.be(3000); done(); }); }); - it('passes nothing be default', function (done) { + it('passes nothing be default', function(done) { var action = makeClientAction({}); - action({}, function (err, params) { + action({}, function(err, params) { expect(params.requestTimeout).be(void 0); done(); }); }); }); - describe('url resolver', function () { - + describe('url resolver', function() { var action = makeClientAction({ urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/<%=thing%>', req: { index: { - type: 'list' + type: 'list', }, id: { - type: 'any' - } + type: 'any', + }, }, opt: { type: { type: 'list', - 'default': '_all' + default: '_all', }, thing: { type: 'any', - 'default': '' - } - } - } - ] + default: '', + }, + }, + }, + ], }); // match a url to the parameters passed in. - it('rejects a url if it required params that are not present', function (done) { - action(params({ - type: ['type1', 'type2'] - }), function (err) { - expect(err).to.be.a(TypeError); - params.check(); - done(); - }); + it('rejects a url if it required params that are not present', function(done) { + action( + params({ + type: ['type1', 'type2'], + }), + function(err) { + expect(err).to.be.a(TypeError); + params.check(); + done(); + } + ); }); - it('uses the default value for optional params', function (done) { - action(params({ - index: 'index1', - id: '1' - }), function (err, resp) { - if (err) { throw err; } - expect(resp.path).to.be('/index1/_all/1/'); - params.check(); - done(); - }); + it('uses the default value for optional params', function(done) { + action( + params({ + index: 'index1', + id: '1', + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.path).to.be('/index1/_all/1/'); + params.check(); + done(); + } + ); }); - it('casts both optional and required args', function (done) { - action(params({ - index: ['index1', 'index2'], - id: '123', - type: ['_all', '-pizza'], - thing: 'poo' - }), function (err, resp) { - if (err) { throw err; } - expect(resp.path).to.be('/index1%2Cindex2/_all%2C-pizza/123/poo'); - params.check(); - done(); - }); + it('casts both optional and required args', function(done) { + action( + params({ + index: ['index1', 'index2'], + id: '123', + type: ['_all', '-pizza'], + thing: 'poo', + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.path).to.be('/index1%2Cindex2/_all%2C-pizza/123/poo'); + params.check(); + done(); + } + ); }); }); - describe('param collection', function () { + describe('param collection', function() { var action = makeClientAction({ params: { a: { type: 'list', required: true }, - b: { type: 'duration', 'default': '15m' }, - q: { type: 'any' } - } + b: { type: 'duration', default: '15m' }, + q: { type: 'any' }, + }, }); - it('collects all of the params into params.query', function (done) { - action(params({ - a: 'pizza', - b: '1M' - }), function (err, resp) { - if (err) { throw err; } - expect(resp.query).to.eql({ + it('collects all of the params into params.query', function(done) { + action( + params({ a: 'pizza', - b: '1M' - }); - params.check(); - done(); - }); + b: '1M', + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.query).to.eql({ + a: 'pizza', + b: '1M', + }); + params.check(); + done(); + } + ); }); - it('includes extra params', function (done) { - action(params({ - a: 'pizza', - b: '3w', - c: 'popular', - }), function (err, resp) { - if (err) { throw err; } - expect(resp.query).to.eql({ + it('includes extra params', function(done) { + action( + params({ a: 'pizza', b: '3w', - c: 'popular' - }); - params.check(); - done(); - }); + c: 'popular', + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.query).to.eql({ + a: 'pizza', + b: '3w', + c: 'popular', + }); + params.check(); + done(); + } + ); }); - it('excludes default values', function (done) { - action(params({ - a: 'pizza', - b: '15m', - }), function (err, resp) { - if (err) { throw err; } - expect(resp.query).to.eql({ - a: 'pizza' - }); - params.check(); - done(); - }); + it('excludes default values', function(done) { + action( + params({ + a: 'pizza', + b: '15m', + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.query).to.eql({ + a: 'pizza', + }); + params.check(); + done(); + } + ); }); - it('does not include non-query param keys', function (done) { - action(params({ - a: 'pizza', - b: '3w', - q: 'beep', - body: '{ "mmm": "json" }', - requestTimeout: 1000, - method: 'head', - ignore: 201 - }), function (err, resp) { - if (err) { throw err; } - expect(resp.query).to.eql({ + it('does not include non-query param keys', function(done) { + action( + params({ a: 'pizza', b: '3w', - q: 'beep' - }); - params.check(); - done(); - }); + q: 'beep', + body: '{ "mmm": "json" }', + requestTimeout: 1000, + method: 'head', + ignore: 201, + }), + function(err, resp) { + if (err) { + throw err; + } + expect(resp.query).to.eql({ + a: 'pizza', + b: '3w', + q: 'beep', + }); + params.check(); + done(); + } + ); }); - it('enforces required params', function (done) { - action(params({ - b: '3w' - }), function (err) { - expect(err).to.be.a(TypeError); - params.check(); - done(); - }); + it('enforces required params', function(done) { + action( + params({ + b: '3w', + }), + function(err) { + expect(err).to.be.a(TypeError); + params.check(); + done(); + } + ); }); - it('does not modify the incoming params object', function () { + it('does not modify the incoming params object', function() { var action = makeClientAction({ url: { req: { - index: { type: 'string' } + index: { type: 'string' }, }, - fmt: '/<%= index %>' + fmt: '/<%= index %>', + }, + }); + action( + params({ + index: 'index', + }), + function(err, resp) { + expect(resp).to.eql({ + method: 'GET', + path: '/index', + query: {}, + }); + params.check(); } - }); - action(params({ - index: 'index' - }), function (err, resp) { - expect(resp).to.eql({ - method: 'GET', - path: '/index', - query: {} - }); - params.check(); - }); + ); }); }); - }); diff --git a/test/unit/specs/connection_abstract.js b/test/unit/specs/connection_abstract.js index f1c3f2753..bb6995a3f 100644 --- a/test/unit/specs/connection_abstract.js +++ b/test/unit/specs/connection_abstract.js @@ -7,45 +7,45 @@ var errors = require('../../../src/lib/errors'); var stub = require('../../utils/auto_release_stub').make(); -describe('Connection Abstract', function () { +describe('Connection Abstract', function() { var host = new Host('localhost:9200'); - it('constructs with defaults for host, and bound', function () { + it('constructs with defaults for host, and bound', function() { var conn = new ConnectionAbstract(host); expect(conn.host).to.be(host); }); - it('requires a valid host', function () { - expect(function () { + it('requires a valid host', function() { + expect(function() { // eslint-disable-next-line no-new new ConnectionAbstract(); }).to.throwError(TypeError); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new ConnectionAbstract({}); }).to.throwError(TypeError); }); - it('required that the request method is overridden', function () { - expect(function () { + it('required that the request method is overridden', function() { + expect(function() { var conn = new ConnectionAbstract(host); conn.request(); }).to.throwError(/overwrit/); }); - describe('#ping', function () { - it('accpets just a callback', function () { + describe('#ping', function() { + it('accpets just a callback', function() { var conn = new ConnectionAbstract(host); stub(conn, 'request'); - var cb = function () {}; + var cb = function() {}; conn.ping(cb); expect(conn.request.callCount).to.eql(1); expect(conn.request.lastCall.args[0]).to.be.a('object'); expect(conn.request.lastCall.args[1]).to.be.a('function'); }); - it('accpets just params', function () { + it('accpets just params', function() { var conn = new ConnectionAbstract(host); stub(conn, 'request'); conn.ping({}); @@ -54,13 +54,13 @@ describe('Connection Abstract', function () { expect(conn.request.lastCall.args[1]).to.be.a('function'); }); - it('allows overriding the requestTimeout, method, and path', function () { + it('allows overriding the requestTimeout, method, and path', function() { var conn = new ConnectionAbstract(host); stub(conn, 'request'); var params = { method: 'HEAD', path: '/', - requestTimeout: 10000 + requestTimeout: 10000, }; conn.ping(params); expect(conn.request.callCount).to.eql(1); @@ -68,7 +68,7 @@ describe('Connection Abstract', function () { expect(conn.request.lastCall.args[1]).to.be.a('function'); }); - it('defaults to the pingTimeout in the config', function () { + it('defaults to the pingTimeout in the config', function() { var conn = new ConnectionAbstract(host, { pingTimeout: 5000 }); var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); @@ -81,64 +81,70 @@ describe('Connection Abstract', function () { expect(clock.timers[_.keys(clock.timers).shift()].delay).to.eql(5000); }); - it('calls it\'s own request method', function () { + it("calls it's own request method", function() { var 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) { + it('sets a timer for the request', function(done) { var conn = new ConnectionAbstract(host); var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var order = 0; - stub(conn, 'request', function (params, cb) { - setTimeout(function () { + stub(conn, 'request', function(params, cb) { + setTimeout(function() { expect(++order).to.eql(2); cb(); }, 10001); }); - conn.ping({ - requestTimeout: 100 - }, function (err) { - expect(++order).to.eql(1); - expect(err).to.be.an(errors.RequestTimeout); - }); + conn.ping( + { + requestTimeout: 100, + }, + function(err) { + expect(++order).to.eql(1); + expect(err).to.be.an(errors.RequestTimeout); + } + ); - process.nextTick(function () { + process.nextTick(function() { clock.tick(1000); clock.tick(10000); done(); }); }); - it('calls the requestAborter if req takes too long', function (done) { + it('calls the requestAborter if req takes too long', function(done) { var conn = new ConnectionAbstract(host); var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var order = 0; - stub(conn, 'request', function (params, cb) { - setTimeout(function () { + stub(conn, 'request', function(params, cb) { + setTimeout(function() { expect(++order).to.eql(3); cb(); }, 10001); - return function () { + return function() { expect(++order).to.eql(1); }; }); - conn.ping({ - requestTimeout: 100 - }, function (err) { - expect(++order).to.eql(2); - expect(err).to.be.an(errors.RequestTimeout); - }); + conn.ping( + { + requestTimeout: 100, + }, + function(err) { + expect(++order).to.eql(2); + expect(err).to.be.an(errors.RequestTimeout); + } + ); - process.nextTick(function () { + process.nextTick(function() { clock.tick(1000); clock.tick(10000); done(); @@ -148,15 +154,15 @@ describe('Connection Abstract', function () { // it('ignores the response from the request if it already aborted'); }); - describe('#setStatus', function () { - it('emits the "status set" event with `new`, `old` & `conn` args', function () { + describe('#setStatus', function() { + it('emits the "status set" event with `new`, `old` & `conn` args', function() { var conn = new ConnectionAbstract(host); var emitted = false; - conn.emit = function (eventName) { + conn.emit = function(eventName) { emitted = { name: eventName, - args: Array.prototype.slice.call(arguments, 1) + args: Array.prototype.slice.call(arguments, 1), }; }; @@ -165,7 +171,7 @@ describe('Connection Abstract', function () { expect(emitted.args).to.eql(['closed', undefined, conn]); }); - it('stores the status in this.status', function () { + it('stores the status in this.status', function() { var conn = new ConnectionAbstract(host); conn.setStatus('closed'); diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index ed6205259..968c70214 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -17,25 +17,25 @@ function listenerCount(emitter, event) { } } -describe('Connection Pool', function () { - describe('Adding/Removing/Syncing Connections', function () { +describe('Connection Pool', function() { + describe('Adding/Removing/Syncing Connections', function() { var pool, host, connection, host2, connection2; - beforeEach(function () { + beforeEach(function() { pool = new ConnectionPool({}); host = new Host({ - port: 999 + port: 999, }); connection = new ConnectionAbstract(host); host2 = new Host({ - port: 2222 + port: 2222, }); connection2 = new ConnectionAbstract(host2); }); - it('#addConnection only adds the connection if it doesn\'t already exist', function () { + it("#addConnection only adds the connection if it doesn't already exist", function() { expect(_.keys(pool.index).length).to.eql(0); pool.addConnection(connection); @@ -45,8 +45,8 @@ describe('Connection Pool', function () { expect(pool._conns.dead).to.eql([]); }); - describe('#removeConnection', function () { - it('removes the connection if it exist', function () { + describe('#removeConnection', function() { + it('removes the connection if it exist', function() { pool.addConnection(connection); pool.removeConnection(connection2); @@ -55,7 +55,7 @@ describe('Connection Pool', function () { expect(_.keys(pool.index).length).to.eql(1); }); - it('closes the connection when it removes it', function () { + it('closes the connection when it removes it', function() { pool.addConnection(connection); expect(connection.status).to.eql('alive'); expect(listenerCount(connection, 'status set')).to.eql(1); @@ -67,7 +67,7 @@ describe('Connection Pool', function () { }); }); - it('#setHosts syncs the list of Hosts with the connections in the index', function () { + it('#setHosts syncs the list of Hosts with the connections in the index', function() { // there should now be two connections pool.setHosts([host, host2]); expect(pool._conns.alive.length).to.eql(2); @@ -92,53 +92,56 @@ describe('Connection Pool', function () { }); }); - describe('Connection selection', function () { + describe('Connection selection', function() { var pool, host, host2; - beforeEach(function () { + beforeEach(function() { pool = new ConnectionPool({}); host = new Host('localhost:9200'); host2 = new Host('localhost:9201'); - pool.setHosts([ - host, - host2 - ]); + pool.setHosts([host, host2]); }); - it('detects if the selector is async', function (done) { - pool.selector = function (list, cb) { + it('detects if the selector is async', function(done) { + pool.selector = function(list, cb) { expect(cb).to.be.a('function'); cb(); }; - pool.select(function (err) { - if (err) { throw err; } + pool.select(function(err) { + if (err) { + throw err; + } done(); }); }); - it('detects if the selector is not async', function (done) { - pool.selector = function () { + it('detects if the selector is not async', function(done) { + pool.selector = function() { expect(arguments.length).to.be(1); }; - pool.select(function (err) { - if (err) { throw err; } + pool.select(function(err) { + if (err) { + throw err; + } done(); }); }); - it('sync selectors should still return async', function (done) { - pool.selector = function (list) { + it('sync selectors should still return async', function(done) { + pool.selector = function(list) { return list[0]; }; var selected = null; - pool.select(function (err, selection) { - if (err) { throw err; } + pool.select(function(err, selection) { + if (err) { + throw err; + } expect(selection.host).to.be(host); selected = selection; done(); @@ -147,51 +150,49 @@ describe('Connection Pool', function () { expect(selected).to.be(null); }); - it('should catch errors in sync selectors', function (done) { - pool.selector = function () { + it('should catch errors in sync selectors', function(done) { + pool.selector = function() { return JSON.notAMethod(); }; - pool.select(function (err) { + pool.select(function(err) { expect(err).be.an(Error); done(); }); }); - }); - 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) { + 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'); stub.autoRelease(clock); var pool = new ConnectionPool({ - deadTimeout: 10000 + deadTimeout: 10000, }); var 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')) + new ConnectionAbstract(new Host('http://localhost:9203')), ]; var pingQueue = _.shuffle(connections); var expectedSelection = pingQueue[pingQueue.length - 1]; - _.each(pingQueue, function (conn) { + _.each(pingQueue, function(conn) { pool.addConnection(conn); - stub(conn, 'ping', function (params, cb) { + stub(conn, 'ping', function(params, cb) { if (typeof params === 'function') { cb = params; } var expectedConn = pingQueue.shift(); expect(conn).to.be(expectedConn); if (pingQueue.length) { - process.nextTick(function () { + process.nextTick(function() { cb(new Error('keep trying')); }); } else { - process.nextTick(function () { + process.nextTick(function() { cb(null, true); }); } @@ -200,7 +201,7 @@ describe('Connection Pool', function () { clock.tick(500); }); - pool.select(function (err, selection) { + pool.select(function(err, selection) { expect(selection).to.be(expectedSelection); expect(pingQueue.length).to.be(0); pool.setHosts([]); @@ -210,19 +211,16 @@ describe('Connection Pool', function () { }); }); - describe('Connection state management', function () { + describe('Connection state management', function() { var pool, host, host2, connection, connection2; - beforeEach(function () { + beforeEach(function() { pool = new ConnectionPool({}); host = new Host('localhost:9200'); host2 = new Host('localhost:9201'); - pool.setHosts([ - host, - host2 - ]); + pool.setHosts([host, host2]); connection = pool.index[host.toString()]; connection2 = pool.index[host2.toString()]; @@ -231,32 +229,38 @@ describe('Connection Pool', function () { expect(pool._conns.dead.length).to.be(0); }); - afterEach(function () { + afterEach(function() { pool.close(); }); - it('moves an alive connection to dead', function () { + it('moves an alive connection to dead', function() { connection.setStatus('dead'); expect(pool._conns.alive.length).to.be(1); expect(pool._conns.dead.length).to.be(1); }); - it('clears and resets the timeout when a connection redies', function () { + it('clears and resets the timeout when a connection redies', function() { var clock = sinon.useFakeTimers(); stub.autoRelease(clock); connection.setStatus('dead'); expect(_.size(clock.timers)).to.eql(1); - var id = _(clock.timers).keys().head(); + var id = _(clock.timers) + .keys() + .head(); // it re-dies connection.setStatus('dead'); expect(_.size(clock.timers)).to.eql(1); - expect(_(clock.timers).keys().head()).to.not.eql(id); + expect( + _(clock.timers) + .keys() + .head() + ).to.not.eql(id); }); - it('does nothing when a connection is re-alive', 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]; @@ -273,7 +277,7 @@ describe('Connection Pool', function () { expect(pool._conns.alive[pool._conns.alive.length - 1]).to.be(last); }); - it('removes all its connection when it closes, causing them to be closed', function () { + it('removes all its connection when it closes, causing them to be closed', function() { pool.close(); expect(pool._conns.alive.length).to.be(0); expect(pool._conns.dead.length).to.be(0); @@ -281,11 +285,10 @@ describe('Connection Pool', function () { expect(connection.status).to.eql('closed'); expect(connection2.status).to.eql('closed'); }); - }); - describe('#getConnections', function () { - it('will return all values from the alive list by default', function () { + describe('#getConnections', function() { + it('will return all values from the alive list by default', function() { var pool = new ConnectionPool({}); pool._conns.alive = new Array(1000); var length = pool._conns.alive.length; @@ -295,50 +298,58 @@ describe('Connection Pool', function () { var result = pool.getConnections(); expect(result.length).to.be(1000); - expect(_.reduce(result, function (sum, num) { - sum += num - return sum; - }, 0)).to.eql(499500); + expect( + _.reduce( + result, + function(sum, num) { + sum += num; + return sum; + }, + 0 + ) + ).to.eql(499500); }); }); - describe('#calcDeadTimeout', function () { - it('should be configurable via config.calcDeadTimeout', function () { + describe('#calcDeadTimeout', function() { + it('should be configurable via config.calcDeadTimeout', function() { var pool = new ConnectionPool({ - calcDeadTimeout: 'flat' + calcDeadTimeout: 'flat', }); - expect(pool.calcDeadTimeout).to.be(ConnectionPool.calcDeadTimeoutOptions.flat); + expect(pool.calcDeadTimeout).to.be( + ConnectionPool.calcDeadTimeoutOptions.flat + ); pool.close(); }); - it('"flat" always returns the base timeout', function () { + it('"flat" always returns the base timeout', function() { var pool = new ConnectionPool({ - calcDeadTimeout: 'flat' + calcDeadTimeout: 'flat', }); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000); expect(pool.calcDeadTimeout(10, 5000)).to.eql(5000); expect(pool.calcDeadTimeout(25, 10000)).to.eql(10000); }); - it('"exponential" always increases the timeout based on the attempts', function () { + it('"exponential" always increases the timeout based on the attempts', function() { var pool = new ConnectionPool({ - calcDeadTimeout: 'exponential' + calcDeadTimeout: 'exponential', }); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000); expect(pool.calcDeadTimeout(10, 5000)).to.be.greaterThan(5000); expect(pool.calcDeadTimeout(25, 10000)).to.be.greaterThan(10000); }); - it('"exponential" produces predicatable results', function () { + it('"exponential" produces predicatable results', function() { var pool = new ConnectionPool({ - calcDeadTimeout: 'exponential' + calcDeadTimeout: 'exponential', }); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000); expect(pool.calcDeadTimeout(4, 10000)).to.eql(40000); // maxes out at 30 minutes by default expect(pool.calcDeadTimeout(25, 30000)).to.eql(18e5); }); - it('"exponential" repects config.maxDeadtimeout', function () { + it('"exponential" repects config.maxDeadtimeout', function() { var pool = new ConnectionPool({ calcDeadTimeout: 'exponential', - maxDeadTimeout: 10000 + maxDeadTimeout: 10000, }); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000); expect(pool.calcDeadTimeout(10, 1000)).to.eql(10000); diff --git a/test/unit/specs/console_logger.js b/test/unit/specs/console_logger.js index e912664ef..9b976802b 100644 --- a/test/unit/specs/console_logger.js +++ b/test/unit/specs/console_logger.js @@ -4,29 +4,28 @@ var sinon = require('sinon'); var expect = require('expect.js'); var parentLog; -beforeEach(function () { +beforeEach(function() { parentLog = new Log(); }); -afterEach(function () { +afterEach(function() { parentLog.close(); }); function makeLogger(parent, levels) { parent = parent || parentLog; var config = { - levels: Log.parseLevels(levels || 'trace') + levels: Log.parseLevels(levels || 'trace'), }; return new ConsoleLogger(parent, config); } require('../../utils/auto_release_stub').make(); -describe('Console Logger', function () { - +describe('Console Logger', function() { require('../generic_logger_tests')(makeLogger); - it('checks before using unique logging functions, falls back to #log()', function () { + it('checks before using unique logging functions, falls back to #log()', function() { var _warning = console.warn; console.warn = null; sinon.stub(console, 'log'); @@ -39,5 +38,4 @@ describe('Console Logger', function () { console.warn = _warning; console.log.restore(); }); - }); diff --git a/test/unit/specs/errors.js b/test/unit/specs/errors.js index fb885c0e3..f31ecb50d 100644 --- a/test/unit/specs/errors.js +++ b/test/unit/specs/errors.js @@ -2,10 +2,10 @@ var errors = require('../../../src/lib/errors'); var expect = require('expect.js'); var _ = require('lodash'); -_.each(errors, function (CustomError, name) { +_.each(errors, function(CustomError, name) { if (name.charAt(0) !== '_') { - describe(name, function () { - it('extend the ErrorAbstract and Error classes', function () { + describe(name, function() { + it('extend the ErrorAbstract and Error classes', function() { var err = new CustomError(); expect(err).to.be.an(Error); expect(err).to.be.an(errors._Abstract); @@ -14,8 +14,8 @@ _.each(errors, function (CustomError, name) { } }); -describe('Error Abstract', function () { - it('provides a stack property in the browser', function () { +describe('Error Abstract', function() { + it('provides a stack property in the browser', function() { var isBrowser = process.browser; process.browser = true; var err = new errors._Abstract(); @@ -25,8 +25,8 @@ describe('Error Abstract', function () { }); }); -describe('StatusCodeError', function () { - it('exposes status code as a number', function () { +describe('StatusCodeError', function() { + it('exposes status code as a number', function() { var err = new errors['404'](); expect(err.status).to.be(404); expect(err.status).to.not.be('404'); diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index cfe27ac17..29ab285d7 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -1,4 +1,4 @@ -describe('File Logger', function () { +describe('File Logger', function() { var Log = require('../../../src/lib/log'); var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; @@ -10,11 +10,11 @@ describe('File Logger', function () { var fs = require('fs'); var stub = require('../../utils/auto_release_stub').make(); - beforeEach(function () { + beforeEach(function() { parentLog = new Log(); }); - afterEach(function () { + afterEach(function() { parentLog.close(); if (logger) { utils.clearWriteStreamBuffer(logger.stream); @@ -25,24 +25,25 @@ describe('File Logger', function () { parent = parent || parentLog; logger = new FileLogger(parent, { levels: Log.parseLevels(levels || 'trace'), - path: 'test.log' + path: 'test.log', }); return logger; } - after(function () { + after(function() { fs.unlinkSync('test.log'); }); require('../generic_logger_tests')(makeLogger); - describe('buffer flush', 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'; + it('writes everything in the buffer to console.error', function() { + var line = + 'This string is written 10 times to create buffered output\n'; var exitHandler; - stub(process, 'once', function (event, handler) { + stub(process, 'once', function(event, handler) { if (event === 'exit') { exitHandler = handler; } @@ -52,13 +53,13 @@ describe('File Logger', function () { var logger = makeLogger(); // write the line 10 times - _.times(10, function () { + _.times(10, function() { logger.onDebug(line); }); // collect everything that is written to fs.appendFileSync var flushedOutput = ''; - stub(fs, 'appendFileSync', function (path, str) { + stub(fs, 'appendFileSync', function(path, str) { flushedOutput += str; }); @@ -70,9 +71,9 @@ describe('File Logger', function () { expect(flushedOutput.match(new RegExp(line, 'g')).length).to.be(9); }); } else { - it('does not fall apart with non streams2 streams', function () { + it('does not fall apart with non streams2 streams', function() { var exitHandler; - stub(process, 'once', function (event, handler) { + stub(process, 'once', function(event, handler) { if (event === 'exit') { exitHandler = handler; } @@ -81,7 +82,7 @@ describe('File Logger', function () { makeLogger(); - expect(function () { + expect(function() { // call the event handler exitHandler.call(process); }).to.not.throwError(); diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index 8429cb998..70fc20724 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -19,40 +19,42 @@ var hostDefaults = { ca: null, ciphers: null, rejectUnauthorized: false, - secureProtocol: null - } + secureProtocol: null, + }, }; -var base64 = function (str) { - var buffer = Buffer.from ? Buffer.from(str, 'utf8') : new Buffer(str, 'utf8') - return buffer.toString('base64') -} +var base64 = function(str) { + var 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 () { +describe('Host class', function() { + describe('construction', function() { + it('properly sets the defaults', function() { var host = new Host(); expect(host).to.eql(hostDefaults); }); - it('accepts a string for query', function () { + it('accepts a string for query', function() { var host = new Host({ query: 'beep=boop' }); expect(host.query).to.eql({ - beep: 'boop' + beep: 'boop', }); }); - it('accepts other generic params', function () { + it('accepts other generic params', function() { var headers = { 'X-Special-Routing-Header': 'pie' }; var 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'); + 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' + ); expectSubObject(host, { protocol: 'http', @@ -60,12 +62,12 @@ describe('Host class', function () { port: 420, path: '/pizza/cheese', query: { - shrooms: 'true' - } + shrooms: 'true', + }, }); }); - it('uses the default port based on the protocol', function () { + it('uses the default port based on the protocol', function() { var host; host = new Host('https://google.com'); @@ -80,7 +82,7 @@ describe('Host class', function () { delete Host.defaultPorts.trift; }); - it('parses simple urls properly', function () { + it('parses simple urls properly', function() { var host; host = new Host('localhost'); @@ -105,8 +107,8 @@ describe('Host class', function () { }); }); - describe('based on the output from url.parse', function () { - it('might cause weird things to happen', 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'); // I imagine most people don't expect @@ -118,69 +120,80 @@ describe('Host class', function () { 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')); + it('will cause extra properties', function() { + var 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); expect(host.path).to.eql('/path'); - expect(host.headers).to.eql({ Authorization: 'Basic ' + base64('joe:diner') }); + expect(host.headers).to.eql({ + Authorization: 'Basic ' + base64('joe:diner'), + }); expect(host.query).to.eql({ - query: 'yes' + query: 'yes', }); expect(host).to.include.keys('slashes', 'hash', 'href', 'search'); }); }); - it('ignores anything that\'s not a string or object-y', function () { + it("ignores anything that's not a string or object-y", function() { var host = new Host(1234); expect(host).to.eql(hostDefaults); }); - it('defaults auth values from the `httpAuth` setting', function () { + it('defaults auth values from the `httpAuth` setting', function() { var host = new Host('http://localhost:9200', { - httpAuth: 'username:password' + httpAuth: 'username:password', }); - expect(host.headers).to.have.property('Authorization', 'Basic ' + base64('username:password')); + expect(host.headers).to.have.property( + 'Authorization', + 'Basic ' + base64('username:password') + ); }); }); - describe('#makeUrl', function () { - it('merges parameters', function () { + describe('#makeUrl', function() { + it('merges parameters', function() { var host = new Host({ path: '/prefix', query: { - user_id: 123 - } + user_id: 123, + }, }); - expect(host.makeUrl({ - path: '/this and that', - query: { - param: 1 - } - })).to.be('http://localhost:9200/prefix/this and that?user_id=123¶m=1'); + expect( + host.makeUrl({ + path: '/this and that', + query: { + param: 1, + }, + }) + ).to.be('http://localhost:9200/prefix/this and that?user_id=123¶m=1'); }); - it('ensures that path starts with a forward-slash', function () { + it('ensures that path starts with a forward-slash', function() { var host = new Host(); host.path = 'prefix'; - expect(host.makeUrl({ path: '/this and that' })) - .to.be('http://localhost:9200/prefix/this and that'); + expect(host.makeUrl({ path: '/this and that' })).to.be( + 'http://localhost:9200/prefix/this and that' + ); }); - it('does not try to prevent double forward-slashes', function () { + it('does not try to prevent double forward-slashes', function() { var host = new Host({ path: 'prefix/' }); - expect(host.makeUrl({ path: '/this and that' })) - .to.be('http://localhost:9200/prefix//this and that'); + expect(host.makeUrl({ path: '/this and that' })).to.be( + 'http://localhost:9200/prefix//this and that' + ); }); - it('creates proper url without any params', function () { + it('creates proper url without any params', function() { var host = new Host({}); expect(host.makeUrl()).to.be('http://localhost:9200/'); @@ -191,58 +204,61 @@ describe('Host class', function () { expect(host.makeUrl()).to.be('http://italy:9200/pie'); }); - it('outputs valid relative urls when the host is empty', function () { + it('outputs valid relative urls when the host is empty', function() { var host = new Host({ host: false, path: '/path', - query: { this: 'that' } + query: { this: 'that' }, }); expect(host + '').to.be('/path?this=that'); }); }); - describe('#toString', function () { - it('produces the same output as makeUrl when it is called without params', function () { + describe('#toString', function() { + it('produces the same output as makeUrl when it is called without params', function() { var host = new Host({ path: '/pasta', - host: 'google.com' + host: 'google.com', }); expect(host.toString()).to.eql(host.makeUrl()); }); }); - describe('#getHeaders', function () { - it('merges the passed in headers with the default headers', function () { + describe('#getHeaders', function() { + it('merges the passed in headers with the default headers', function() { var host = new Host({ headers: { 'Joe-Smith': 'present' } }); - expect(host.getHeaders({ - 'John-Smith': 'present' - })).to.eql({ + expect( + host.getHeaders({ + 'John-Smith': 'present', + }) + ).to.eql({ 'John-Smith': 'present', - 'Joe-Smith': 'present' + 'Joe-Smith': 'present', }); }); - it('overrides the default headers with the passed in headers', function () { + it('overrides the default headers with the passed in headers', function() { var host = new Host({ headers: { 'Joe-Smith': 'present' } }); - expect(host.getHeaders({ + expect( + host.getHeaders({ + 'John-Smith': 'present', + 'Joe-Smith': 'absent', + }) + ).to.eql({ 'John-Smith': 'present', - 'Joe-Smith': 'absent' - })).to.eql({ - 'John-Smith': 'present', - 'Joe-Smith': 'absent' + 'Joe-Smith': 'absent', }); }); - it('adds Accept-Encoding header when the suggestCompression setting is true', function () { + it('adds Accept-Encoding header when the suggestCompression setting is true', function() { var host = new Host({ suggestCompression: true }); expect(host.getHeaders()).to.eql({ - 'Accept-Encoding': 'gzip,deflate' + 'Accept-Encoding': 'gzip,deflate', }); }); }); - }); diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index b947fa494..4edae0ec6 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -1,5 +1,4 @@ -describe('Http Connector', function () { - +describe('Http Connector', function() { var _ = require('lodash'); var expect = require('expect.js'); var nock = require('nock'); @@ -22,7 +21,7 @@ describe('Http Connector', function () { var stub = require('../../utils/auto_release_stub').make(); function makeStubReqMethod(prep) { - return function (params, cb) { + return function(params, cb) { var req = new MockRequest(); if (prep) { prep(req, params, cb); @@ -32,21 +31,21 @@ describe('Http Connector', function () { } function whereReqDies(withErr) { - return function (req) { - process.nextTick(function () { + return function(req) { + process.nextTick(function() { // causes the request to quit and callback req.emit('error', withErr || void 0); }); }; } - describe('Constructor', function () { - it('creates an object that extends ConnectionAbstract', function () { + describe('Constructor', function() { + it('creates an object that extends ConnectionAbstract', function() { var con = new HttpConnection(new Host()); expect(con).to.be.a(ConnectionAbstract); }); - it('sets certain defaults', function () { + it('sets certain defaults', function() { var con = new HttpConnection(new Host()); expect(con.hand).to.be(require('http')); @@ -57,27 +56,31 @@ describe('Http Connector', function () { // requestTimeout }); - it('expects the host to have a protocol of http or https', function () { - expect(function () { + it('expects the host to have a protocol of http or https', function() { + expect(function() { // eslint-disable-next-line no-new new HttpConnection(new Host('thrifty://es.com/stuff')); }).to.throwError(/invalid protocol/i); }); - it('allows defining a custom agent', function () { + it('allows defining a custom agent', function() { var football = {}; - var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) }); + var 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) }); + it('allows setting agent to false', function() { + var con = new HttpConnection(new Host(), { + createNodeAgent: _.constant(false), + }); expect(con.agent).to.be(false); }); }); - describe('#makeReqParams', function () { - it('properly reads the host object', function () { + 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(); @@ -90,34 +93,38 @@ describe('Http Connector', function () { port: 9200, path: '/pizza/cheese?shrooms=true', headers: host.headers, - agent: con.agent + agent: con.agent, }); }); - it('merges a query object with the hosts\'', function () { - var con = new HttpConnection(new Host({ - query: { - user_id: 123 - } - })); + it("merges a query object with the hosts'", function() { + var con = new HttpConnection( + new Host({ + query: { + user_id: 123, + }, + }) + ); var reqParams = con.makeReqParams({ query: { - jvm: 'yes' - } + jvm: 'yes', + }, }); expect(reqParams.path).to.eql('/?user_id=123&jvm=yes'); }); - it('merges the path prefix', function () { - var con = new HttpConnection(new Host('https://google.com/path/prefix/for/user/1')); + it('merges the path prefix', function() { + var con = new HttpConnection( + new Host('https://google.com/path/prefix/for/user/1') + ); var reqParams = con.makeReqParams({ method: 'GET', path: '/items', query: { - q: 'pizza' - } + q: 'pizza', + }, }); expectSubObject(reqParams, { @@ -125,15 +132,17 @@ describe('Http Connector', function () { }); }); - it('merges the query', function () { - var con = new HttpConnection(new Host('http://google.com/pref-x?userId=12345&token=42069')); + it('merges the query', function() { + var con = new HttpConnection( + new Host('http://google.com/pref-x?userId=12345&token=42069') + ); var reqParams = con.makeReqParams({ method: 'PUT', path: '/stuff', query: { - q: 'pizza' - } + q: 'pizza', + }, }); expectSubObject(reqParams, { @@ -141,12 +150,12 @@ describe('Http Connector', function () { }); }); - it('Works well with minimum params', function () { + it('Works well with minimum params', function() { var con = new HttpConnection(new Host('http://google.com')); var reqParams = con.makeReqParams({ method: 'PUT', - path: '/stuff' + path: '/stuff', }); expect(reqParams).to.eql({ @@ -156,20 +165,20 @@ describe('Http Connector', function () { port: 80, path: '/stuff', headers: null, - agent: con.agent + agent: con.agent, }); }); }); - describe('#request', function () { - beforeEach(function () { + describe('#request', function() { + beforeEach(function() { stub(http, 'request', makeStubReqMethod(whereReqDies())); stub(https, 'request', makeStubReqMethod(whereReqDies())); }); - it('calls http based on the host', function (done) { + it('calls http based on the host', function(done) { var con = new HttpConnection(new Host('http://google.com')); - con.request({}, function () { + con.request({}, function() { expect(http.request.callCount).to.be(1); expect(https.request.callCount).to.be(0); expect(http.request.lastCall.args[0].agent).to.be.a(AgentKeepAlive); @@ -177,17 +186,19 @@ describe('Http Connector', function () { }); }); - it('calls https based on the host', function (done) { + it('calls https based on the host', function(done) { var con = new HttpConnection(new Host('https://google.com')); - con.request({}, function () { + con.request({}, function() { expect(http.request.callCount).to.be(0); expect(https.request.callCount).to.be(1); - expect(https.request.lastCall.args[0].agent).to.be.a(AgentKeepAlive.HttpsAgent); + expect(https.request.lastCall.args[0].agent).to.be.a( + AgentKeepAlive.HttpsAgent + ); done(); }); }); - it('does not log error events', function (done) { + it('does not log error events', function(done) { var con = new HttpConnection(new Host('http://google.com')); stub(con.log, 'error'); @@ -197,9 +208,13 @@ describe('Http Connector', function () { stub(con.log, 'debug'); http.request.restore(); - stub(http, 'request', makeStubReqMethod(whereReqDies(new Error('actual error')))); + stub( + http, + 'request', + makeStubReqMethod(whereReqDies(new Error('actual error'))) + ); - con.request({}, function (err) { + con.request({}, function(err) { // error should have been sent to the expect(err.message).to.eql('actual error'); @@ -214,14 +229,16 @@ describe('Http Connector', function () { }); }); - it('logs error events', function (done) { + it('logs error events', function(done) { var con = new HttpConnection(new Host('http://google.com')); stub(con.log, 'error'); - http.request.func = makeStubReqMethod(whereReqDies(new Error('actual error'))); + http.request.func = makeStubReqMethod( + whereReqDies(new Error('actual error')) + ); - con.request({}, function (err) { + con.request({}, function(err) { // error should have been sent to the expect(err.message).to.eql('actual error'); @@ -231,25 +248,29 @@ describe('Http Connector', function () { }); }); - it('calls back with error when http.request throws an error', function (done) { - var con = new HttpConnection(new Host('http://google.com/thisisinvalid\uffe2')); + it('calls back with error when http.request throws an error', function(done) { + var con = new HttpConnection( + new Host('http://google.com/thisisinvalid\uffe2') + ); stub(con.log, 'error'); - con.request({}, function (err) { - expect(err.message).to.eql('ERR_UNESCAPED_CHARACTERS: /thisisinvalid\uffe2'); + con.request({}, function(err) { + expect(err.message).to.eql( + 'ERR_UNESCAPED_CHARACTERS: /thisisinvalid\uffe2' + ); done(); }); }); }); - describe('#request with incomming message error', function () { + describe('#request with incomming message error', function() { function makeStubReqWithMsgWhichErrorsMidBody(err) { - return makeStubReqMethod(function (req, params, cb) { - process.nextTick(function () { + return makeStubReqMethod(function(req, params, cb) { + process.nextTick(function() { var incom = new MockIncommingMessage(); incom.statusCode = 200; - setTimeout(function () { + setTimeout(function() { incom.emit('data', '{ "not json"'); incom.emit('error', err || new Error('Socket is dead now...')); }, 20); @@ -258,72 +279,77 @@ describe('Http Connector', function () { }); } - it('does not log errors', function (done) { + it('does not log errors', function(done) { var con = new HttpConnection(new Host('https://google.com')); stub(con.log, 'error'); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); - con.request({}, function () { + con.request({}, function() { expect(con.log.error.callCount).to.eql(0); done(); }); }); - it('passes the original error on', function (done) { + it('passes the original error on', function(done) { var con = new HttpConnection(new Host('https://google.com')); - stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :('))); + stub( + https, + 'request', + makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :(')) + ); - con.request({}, function (err) { + con.request({}, function(err) { expect(err).to.be.an(Error); expect(err.message).to.eql('no more message :('); done(); }); }); - it('does not pass the partial body along', function (done) { + it('does not pass the partial body along', function(done) { var con = new HttpConnection(new Host('https://google.com')); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); - con.request({}, function (err, resp) { + con.request({}, function(err, resp) { expect(resp).to.be(undefined); done(); }); }); - it('does not pass the status code along', function (done) { + it('does not pass the status code along', function(done) { var con = new HttpConnection(new Host('https://google.com')); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); - con.request({}, function (err, resp, status) { + con.request({}, function(err, resp, status) { expect(status).to.be(undefined); done(); }); }); }); - describe('#request\'s responder', function () { - it('collects the whole request body', function (done) { + 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" }'; - server - .get('/users/1') - .reply(200, body); + server.get('/users/1').reply(200, body); - con.request({ - method: 'GET', - path: '/users/1' - }, function (err, resp, status) { - expect(err).to.be(undefined); - expect(resp).to.eql(body); - expect(status).to.eql(200); - server.done(); - done(); - }); + con.request( + { + method: 'GET', + path: '/users/1', + }, + function(err, resp, status) { + expect(err).to.be(undefined); + expect(resp).to.eql(body); + expect(status).to.eql(200); + server.done(); + done(); + } + ); }); - it('collects the whole request body (gzip compressed)', function (done) { + 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 = []; @@ -331,25 +357,28 @@ describe('Http Connector', function () { elements.push({ USER: 'doc' }); } var body = JSON.stringify(elements); - zlib.gzip(body, function (err, compressedBody) { + zlib.gzip(body, function(err, compressedBody) { server .get('/users/1') .reply(200, compressedBody, { 'Content-Encoding': 'gzip' }); - con.request({ - method: 'GET', - path: '/users/1' - }, function (err, resp, status) { - expect(err).to.be(undefined); - expect(resp).to.eql(body); - expect(status).to.eql(200); - server.done(); - done(); - }); + con.request( + { + method: 'GET', + path: '/users/1', + }, + function(err, resp, status) { + expect(err).to.be(undefined); + expect(resp).to.eql(body); + expect(status).to.eql(200); + server.done(); + done(); + } + ); }); }); - it('collects the whole request body (deflate compressed)', function (done) { + 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 = []; @@ -357,127 +386,144 @@ describe('Http Connector', function () { elements.push({ USER: 'doc' }); } var body = JSON.stringify(elements); - zlib.deflate(body, function (err, compressedBody) { + zlib.deflate(body, function(err, compressedBody) { server .get('/users/1') .reply(200, compressedBody, { 'Content-Encoding': 'deflate' }); - con.request({ - method: 'GET', - path: '/users/1' - }, function (err, resp, status) { - expect(err).to.be(undefined); - expect(resp).to.eql(body); - expect(status).to.eql(200); - server.done(); - done(); - }); + con.request( + { + method: 'GET', + path: '/users/1', + }, + function(err, resp, status) { + expect(err).to.be(undefined); + expect(resp).to.eql(body); + expect(status).to.eql(200); + server.done(); + done(); + } + ); }); }); - it('Can handle decompression errors', function (done) { + 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'; - server - .get('/users/1') - .reply(200, body, { 'Content-Encoding': 'gzip' }); + server.get('/users/1').reply(200, body, { 'Content-Encoding': 'gzip' }); - con.request({ - method: 'GET', - path: '/users/1' - }, function (err, resp, status) { - expect(err).to.be.an(Error); - expect(resp).to.eql(undefined); - expect(status).to.eql(undefined); - server.done(); - done(); - }); + con.request( + { + method: 'GET', + path: '/users/1', + }, + function(err, resp, status) { + expect(err).to.be.an(Error); + expect(resp).to.eql(undefined); + expect(status).to.eql(undefined); + server.done(); + done(); + } + ); }); - it('Ignores serialization errors', function (done) { + 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":'; // partial body - server - .get('/users/1') - .reply(200, body); + server.get('/users/1').reply(200, body); - con.request({ - method: 'GET', - path: '/users/1' - }, function (err, resp, status) { - expect(err).to.be(undefined); - expect(resp).to.eql(body); - expect(status).to.eql(200); - done(); - }); + con.request( + { + method: 'GET', + path: '/users/1', + }, + function(err, resp, status) { + expect(err).to.be(undefined); + expect(resp).to.eql(body); + expect(status).to.eql(200); + done(); + } + ); }); }); - describe('HTTP specifics', function () { - it('uses TCP no delay', function (done) { + describe('HTTP specifics', function() { + it('uses TCP no delay', function(done) { var con = new HttpConnection(new Host('localhost')); stub(http.ClientRequest.prototype, 'setNoDelay'); - var server = nock('http://localhost').get('/').reply(200); + var server = nock('http://localhost') + .get('/') + .reply(200); - con.request({}, function () { + con.request({}, function() { expect(http.ClientRequest.prototype.setNoDelay.callCount).to.eql(1); - expect(http.ClientRequest.prototype.setNoDelay.lastCall.args[0]).to.eql(true); + expect(http.ClientRequest.prototype.setNoDelay.lastCall.args[0]).to.eql( + true + ); server.done(); done(); }); }); - it('sets the Content-Length header properly', function (done) { + it('sets the Content-Length header properly', function(done) { var con = new HttpConnection(new Host('localhost')); stub(http.ClientRequest.prototype, 'setHeader'); - var server = nock('http://localhost').get('/').reply(200); + var server = nock('http://localhost') + .get('/') + .reply(200); var body = 'pasta and 𝄞'; expect(body.length).to.eql(12); // nope expect(Buffer.byteLength(body, 'utf8')).to.eql(14); // yep - con.request({ - body: body - }, function () { - expect(http.ClientRequest.prototype.setHeader.args.find((arg) => arg[0] === 'Content-Length')).to.eql(['Content-Length', 14]); - server.done(); - done(); - }); + con.request( + { + body: body, + }, + function() { + expect( + http.ClientRequest.prototype.setHeader.args.find( + arg => arg[0] === 'Content-Length' + ) + ).to.eql(['Content-Length', 14]); + server.done(); + done(); + } + ); }); - it('does not set the Accept-Encoding header by default', function (done) { + 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') - .matchHeader('Accept-Encoding', function (v) { + .matchHeader('Accept-Encoding', function(v) { + return v === undefined; + }) + .get('/') + .once() + .reply(200, respBody); - return v === undefined; - }) - .get('/') - .once() - .reply(200, respBody); - - con.request({}, function (err, resp) { + con.request({}, function(err, resp) { expect(resp).to.be(respBody); server.done(); done(); }); }); - it('sets the Accept-Encoding header when specified', function (done) { + 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') - .matchHeader('Accept-Encoding', 'gzip,deflate') - .get('/') - .once() - .reply(200, respBody); + .matchHeader('Accept-Encoding', 'gzip,deflate') + .get('/') + .once() + .reply(200, respBody); - con.request({}, function (err, resp) { + con.request({}, function(err, resp) { expect(resp).to.be(respBody); server.done(); done(); @@ -485,21 +531,23 @@ describe('Http Connector', function () { }); }); - describe('Connection cleanup', function () { - it('destroys any connections created', function (done) { + 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 - var server = cp.fork(fixture('keepalive_server.js')) - .on('message', function (port) { + var server = cp + .fork(fixture('keepalive_server.js')) + .on('message', function(port) { client.send(port); }); - var client = cp.fork(fixture('keepalive.js')) - .on('message', function (output) { + var client = cp + .fork(fixture('keepalive.js')) + .on('message', function(output) { expect(output).to.have.property('remaining', 0); expect(output).to.have.property('timeouts', 0); server.kill('SIGKILL'); @@ -507,30 +555,30 @@ describe('Http Connector', function () { client.disconnect(); } - timeout = setTimeout(function () { + timeout = setTimeout(function() { client.removeListener('exit'); done(new Error('process should have closed by now')); }, 2000); }) - .on('exit', function () { + .on('exit', function() { clearTimeout(timeout); done(); }); }); - it('properly removes all elements from the socket', function () { + it('properly removes all elements from the socket', function() { var con = new HttpConnection(new Host('localhost')); var sockets = [ - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} }, - { destroy: function () {} } + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, + { destroy: function() {} }, ]; var name = con.agent.getName(parseUrl('http://localhost/')); con.agent.sockets[name] = sockets; @@ -538,5 +586,4 @@ describe('Http Connector', function () { expect(sockets).to.eql([]); }); }); - }); diff --git a/test/unit/specs/json_serializer.js b/test/unit/specs/json_serializer.js index 3bf8e0c95..b8e4afa5f 100644 --- a/test/unit/specs/json_serializer.js +++ b/test/unit/specs/json_serializer.js @@ -1,4 +1,4 @@ -describe('JSON serializer', function () { +describe('JSON serializer', function() { var JsonSerializer = require('../../../src/lib/serializers/json'); var expect = require('expect.js'); var sinon = require('sinon'); @@ -8,8 +8,8 @@ describe('JSON serializer', function () { return new JsonSerializer(); } - describe('#serialize', function () { - it('defers to JSON.stringify', function () { + describe('#serialize', function() { + it('defers to JSON.stringify', function() { var stub = sinon.stub(JSON, 'stringify'); var ser = makeSerializer(); ser.serialize({ some: 'object' }); @@ -17,30 +17,30 @@ describe('JSON serializer', function () { stub.restore(); }); - it('does not modify strings', function () { + it('does not modify strings', function() { var ser = makeSerializer(); var thing = 'pretend that I am serialized'; expect(ser.serialize(thing)).to.be(thing); }); - it('returns nothing for invalid values', function () { + it('returns nothing for invalid values', function() { var ser = makeSerializer(); expect(ser.serialize(null)).to.be(undefined); expect(ser.serialize(false)).to.be(undefined); }); - it('throws serialization errors', function () { + it('throws serialization errors', function() { var ser = makeSerializer(); var thing = { name: 'thing' }; thing.self = thing; - expect(function () { + expect(function() { ser.serialize(thing); }).to.throwError(); }); - it('utilizes replacer or spaces if passed', function () { + it('utilizes replacer or spaces if passed', function() { sinon.spy(JSON, 'stringify'); var ser = makeSerializer(); var thing = { name: 'thing' }; @@ -49,7 +49,7 @@ describe('JSON serializer', function () { JSON.stringify.restore(); }); - it('should call JSON.stringify with value only', function () { + it('should call JSON.stringify with value only', function() { sinon.spy(JSON, 'stringify'); var ser = makeSerializer(); var thing = { name: 'thing' }; @@ -59,15 +59,15 @@ describe('JSON serializer', function () { }); }); - describe('#deserialize', function () { - it('defers to JSON.parse', function () { + describe('#deserialize', function() { + it('defers to JSON.parse', function() { stub(JSON, 'parse'); var ser = makeSerializer(); ser.deserialize('{ "some": "JSON" }'); expect(JSON.parse.callCount).to.eql(1); }); - it('ignores non string values', function () { + it('ignores non string values', function() { var ser = makeSerializer(); var thing = ['pretend that I am not here']; expect(ser.deserialize(thing)).to.be(undefined); @@ -75,42 +75,39 @@ describe('JSON serializer', function () { expect(ser.deserialize(false)).to.be(undefined); }); - it('catches serialization errors, returns nothing', function () { + it('catches serialization errors, returns nothing', function() { var ser = makeSerializer(); - var thing = '{ name: \'thing\' }'; + var thing = "{ name: 'thing' }"; expect(ser.deserialize(thing)).to.be(undefined); }); }); - describe('#bulkBody', function () { - var body = [ - { index: 'thing' }, - { document: 'hi' } - ]; + describe('#bulkBody', function() { + var body = [{ index: 'thing' }, { document: 'hi' }]; var bulk = '{"index":"thing"}\n{"document":"hi"}\n'; - it('creates a string out of an array of obejcts', function () { + it('creates a string out of an array of obejcts', function() { var ser = makeSerializer(); expect(ser.bulkBody(body)).to.eql(bulk); }); - it('adds a newline to the end of strings', function () { + it('adds a newline to the end of strings', function() { var ser = makeSerializer(); expect(ser.bulkBody(bulk.substr(0, bulk.length - 1))).to.eql(bulk); }); - it('throws an error for anything else', function () { + it('throws an error for anything else', function() { var ser = makeSerializer(); - expect(function () { + expect(function() { ser.bulkBody({}); }).to.throwError(); - expect(function () { + expect(function() { ser.bulkBody(null); }).to.throwError(); - expect(function () { + expect(function() { ser.bulkBody(false); }).to.throwError(); }); diff --git a/test/unit/specs/log.js b/test/unit/specs/log.js index c6000a5f9..e58536c01 100644 --- a/test/unit/specs/log.js +++ b/test/unit/specs/log.js @@ -2,119 +2,110 @@ var Log = require('../../../src/lib/log'); var _ = require('lodash'); var expect = require('expect.js'); -describe('Log class', function () { - describe('::parseLevels', function () { - it('accepts a string and returns it and the other levels below it', function () { +describe('Log class', function() { + describe('::parseLevels', function() { + it('accepts a string and returns it and the other levels below it', function() { expect(Log.parseLevels('trace')).to.eql([ 'error', 'warning', 'info', 'debug', - 'trace' + 'trace', ]); }); - it('accepts and validates an array of levels', function () { + it('accepts and validates an array of levels', function() { expect(Log.parseLevels(['warning', 'info'])).to.eql(['warning', 'info']); }); - it('throws an error when an invalid string is supplied', function () { - expect(function () { + it('throws an error when an invalid string is supplied', function() { + expect(function() { Log.parseLevels('INVALID'); }).to.throwError(/invalid logging level/); }); - it('throws an error when an invalid string is supplied in side an array', function () { - expect(function () { + it('throws an error when an invalid string is supplied in side an array', function() { + expect(function() { Log.parseLevels(['error', 'INVALID']); }).to.throwError(/invalid logging level/); }); }); - describe('#addOutput', function () { + describe('#addOutput', function() { var log; - Log.loggers.stub = function (log, config) { + Log.loggers.stub = function(log, config) { this.config = config; }; - beforeEach(function () { + beforeEach(function() { log = new Log(); }); - it('returns the newly created logger', function () { + it('returns the newly created logger', function() { expect(log.addOutput({ type: 'stub' })).to.be.a(Log.loggers.stub); }); - it('Accepts a config object with `level: "{{level}}"`', function () { + it('Accepts a config object with `level: "{{level}}"`', function() { var logger = log.addOutput({ type: 'stub', - level: 'warning' + level: 'warning', }); - expect(logger.config.levels).to.eql([ - 'error', 'warning' - ]); + expect(logger.config.levels).to.eql(['error', 'warning']); }); - it('Accepts a config object with `level: ["{{level}}"]`', function () { + it('Accepts a config object with `level: ["{{level}}"]`', function() { var logger = log.addOutput({ type: 'stub', - level: ['warning'] + level: ['warning'], }); - expect(logger.config.levels).to.eql([ - 'warning' - ]); + expect(logger.config.levels).to.eql(['warning']); }); - - it('Accepts a config object with `levels: "{{level}}"`', function () { + it('Accepts a config object with `levels: "{{level}}"`', function() { var logger = log.addOutput({ type: 'stub', - levels: 'warning' + levels: 'warning', }); - expect(logger.config.levels).to.eql([ - 'error', 'warning' - ]); + expect(logger.config.levels).to.eql(['error', 'warning']); }); - it('Accepts a config object with `levels: ["{{level}}"]`', function () { + it('Accepts a config object with `levels: ["{{level}}"]`', function() { var logger = log.addOutput({ type: 'stub', - level: ['warning'] + level: ['warning'], }); - expect(logger.config.levels).to.eql([ - 'warning' - ]); + expect(logger.config.levels).to.eql(['warning']); }); }); - describe('#join', function () { - it('joins strings together with spaces', function () { + describe('#join', function() { + it('joins strings together with spaces', function() { expect(Log.join(['foo', 'bar'])).to.eql('foo bar'); }); - it('stringifies objects', function () { + it('stringifies objects', function() { expect(Log.join([{ foo: 'bar' }])).to.eql('{\n "foo": "bar"\n}\n'); }); - it('fully stringifies deeply nested objects', function () { + it('fully stringifies deeply nested objects', function() { var object = { foo: { bar: { baz: 'value' } } }; var expected = '{\n "bar": {\n "baz": "value"\n }\n}\n'; expect(Log.join(object)).to.eql(expected); }); }); - describe('instance without any outputs', function () { + describe('instance without any outputs', function() { var log; - beforeEach(function () { + beforeEach(function() { log = new Log(); }); - it('should not emit any events', function () { - log.emit = function () { + it('should not emit any events', function() { + log.emit = function() { throw new Error('Emit should not be called'); }; @@ -123,37 +114,36 @@ describe('Log class', function () { log.warning(); log.debug(); log.trace(); - }); }); - describe('instance without one output listening to all events', function () { + describe('instance without one output listening to all events', function() { var log, call; - beforeEach(function () { + beforeEach(function() { call = void 0; log = new Log({ log: [ { - type: function (log) { + type: function(log) { log.on('error', _.noop); log.on('warning', _.noop); log.on('info', _.noop); log.on('debug', _.noop); log.on('trace', _.noop); - } - } - ] + }, + }, + ], }); - log.emit = function (eventName) { + log.emit = function(eventName) { call = { event: eventName, - args: Array.prototype.slice.call(arguments, 1) + args: Array.prototype.slice.call(arguments, 1), }; }; }); - it('should emit an "error" event with an Error object arg', function () { + it('should emit an "error" event with an Error object arg', function() { var err = new Error('error'); log.error(err); expect(call.event).to.eql('error'); @@ -167,40 +157,45 @@ describe('Log class', function () { expect(call.args[0].message).to.eql('error'); }); - it('should emit a "warning" event with a single message arg for #warning calls', function () { + it('should emit a "warning" event with a single message arg for #warning calls', function() { log.warning('shit!'); expect(call.event).to.eql('warning'); expect(call.args.length).to.be(1); expect(call.args[0]).to.eql('shit!'); }); - it('should emit a "info" event with a single message arg for #info calls', function () { + it('should emit a "info" event with a single message arg for #info calls', function() { log.info('look out!'); expect(call.event).to.eql('info'); expect(call.args.length).to.be(1); expect(call.args[0]).to.eql('look out!'); }); - it('should emit a "debug" event with a single message arg for #debug calls', function () { + it('should emit a "debug" event with a single message arg for #debug calls', function() { log.debug('here'); expect(call.event).to.eql('debug'); expect(call.args.length).to.be(1); expect(call.args[0]).to.eql('here'); }); - it('should emit a trace event for trace events, with normalized request details arg', function () { + it('should emit a trace event for trace events, with normalized request details arg', function() { log.trace('GET', 'http://localhost:9200/_cluster/nodes', '', '', 200); expect(call.event).to.eql('trace'); expect(call.args.length).to.be(1); expect(call.args[0]).to.have.property('method', 'GET'); - expect(call.args[0]).to.have.property('url', 'http://localhost:9200/_cluster/nodes'); + expect(call.args[0]).to.have.property( + 'url', + 'http://localhost:9200/_cluster/nodes' + ); expect(call.args[0]).to.have.property('status', 200); }); }); - 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' } }); + 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' }, + }); expect(log.listenerCount('error')).to.eql(1); expect(log.listenerCount('warning')).to.eql(0); expect(log.listenerCount('info')).to.eql(0); @@ -208,7 +203,7 @@ describe('Log class', function () { expect(log.listenerCount('trace')).to.eql(0); }); - it('accepts a string and treat it as a log level', function () { + it('accepts a string and treat it as a log level', function() { var log = new Log({ log: 'error' }); expect(log.listenerCount('error')).to.eql(1); expect(log.listenerCount('warning')).to.eql(0); @@ -217,7 +212,7 @@ describe('Log class', function () { expect(log.listenerCount('trace')).to.eql(0); }); - it('accepts an array of strings and treat it as a log level config', function () { + it('accepts an array of strings and treat it as a log level config', function() { var log = new Log({ log: ['error', 'trace'] }); expect(log.listenerCount('error')).to.eql(1); expect(log.listenerCount('warning')).to.eql(0); @@ -226,7 +221,7 @@ describe('Log class', function () { expect(log.listenerCount('trace')).to.eql(1); }); - it('accepts an array of output config objects', function () { + it('accepts an array of output config objects', function() { var log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] }); expect(log.listenerCount('error')).to.eql(2); expect(log.listenerCount('warning')).to.eql(1); @@ -235,28 +230,28 @@ describe('Log class', function () { expect(log.listenerCount('trace')).to.eql(1); }); - it('rejects numbers and other truthy data-types', function () { - expect(function () { + it('rejects numbers and other truthy data-types', function() { + expect(function() { // eslint-disable-next-line no-new new Log({ log: 1515 }); }).to.throwError(/invalid logging output config/i); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Log({ log: /regexp/ }); }).to.throwError(/invalid logging output config/i); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Log({ log: new Date() }); }).to.throwError(/invalid logging output config/i); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Log({ log: [1515] }); }).to.throwError(/invalid logging output config/i); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Log({ log: [/regexp/] }); }).to.throwError(/invalid logging output config/i); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Log({ log: [new Date()] }); }).to.throwError(/invalid logging output config/i); diff --git a/test/unit/specs/nodes_to_host_callback.js b/test/unit/specs/nodes_to_host_callback.js index cd161ace3..43a414769 100644 --- a/test/unit/specs/nodes_to_host_callback.js +++ b/test/unit/specs/nodes_to_host_callback.js @@ -1,4 +1,4 @@ -describe('Nodes to host callback', function () { +describe('Nodes to host callback', function() { var callback = require('../../../src/lib/nodes_to_host'); var expect = require('expect.js'); @@ -7,8 +7,8 @@ describe('Nodes to host callback', function () { var nodes20 = require('../../fixtures/short_node_list.2.0.json'); var nodes50 = require('../../fixtures/short_node_list.5.0.json'); - context('0.x style', function () { - it('properly creates host objects', function () { + context('0.x style', function() { + it('properly creates host objects', function() { expect(callback(nodes90)).to.eql([ { host: '192.168.1.1', @@ -16,8 +16,8 @@ describe('Nodes to host callback', function () { _meta: { id: 'id1', name: 'name1', - version: '0.90.14-SNAPSHOT' - } + version: '0.90.14-SNAPSHOT', + }, }, { host: 'localhost', @@ -25,15 +25,15 @@ describe('Nodes to host callback', function () { _meta: { id: 'id2', name: 'name2', - version: '0.90.14-SNAPSHOT' - } - } + version: '0.90.14-SNAPSHOT', + }, + }, ]); }); }); - context('1.0 nodes style', function () { - it('properly creates host objects', function () { + context('1.0 nodes style', function() { + it('properly creates host objects', function() { expect(callback(nodes10)).to.eql([ { host: '10.10.10.100', @@ -41,8 +41,8 @@ describe('Nodes to host callback', function () { _meta: { id: 'id1', name: 'name1', - version: '1.0.4-SNAPSHOT' - } + version: '1.0.4-SNAPSHOT', + }, }, { host: 'published.hostname', @@ -50,15 +50,15 @@ describe('Nodes to host callback', function () { _meta: { id: 'id2', name: 'name2', - version: '1.0.4-SNAPSHOT' - } - } + version: '1.0.4-SNAPSHOT', + }, + }, ]); }); }); - context('2.0 nodes style', function () { - it('properly creates host objects', function () { + context('2.0 nodes style', function() { + it('properly creates host objects', function() { expect(callback(nodes20)).to.eql([ { host: '127.0.0.1', @@ -66,8 +66,8 @@ describe('Nodes to host callback', function () { _meta: { id: 'id1', name: 'name1', - version: '2.0.3-SNAPSHOT' - } + version: '2.0.3-SNAPSHOT', + }, }, { host: 'published.hostname', @@ -75,15 +75,15 @@ describe('Nodes to host callback', function () { _meta: { id: 'id2', name: 'name2', - version: '2.0.3-SNAPSHOT' - } - } + version: '2.0.3-SNAPSHOT', + }, + }, ]); }); }); - context('5.0 nodes style', function () { - it('properly creates host objects', function () { + context('5.0 nodes style', function() { + it('properly creates host objects', function() { expect(callback(nodes50)).to.eql([ { host: '127.0.0.1', @@ -91,8 +91,8 @@ describe('Nodes to host callback', function () { _meta: { id: 'id1', name: 'name1', - version: '5.0.3' - } + version: '5.0.3', + }, }, { host: 'published.hostname', @@ -100,34 +100,32 @@ describe('Nodes to host callback', function () { _meta: { id: 'id2', name: 'name2', - version: '5.0.3' - } - } + version: '5.0.3', + }, + }, ]); }); }); - - it('ignores hosts that don\'t have an http_host property', function () { + it("ignores hosts that don't have an http_host property", function() { var hosts = callback({ node_id: { - not: 'much of a node' - } + not: 'much of a node', + }, }); expect(hosts.length).to.be(0); }); - it('throws an error when the host property is not formatted properly', function () { - expect(function () { + it('throws an error when the host property is not formatted properly', function() { + expect(function() { callback({ node_id: { http: { - publish_address: 'not actually an http host' - } - } + publish_address: 'not actually an http host', + }, + }, }); }).to.throwException(/^Malformed http.publish_address/); }); - }); diff --git a/test/unit/specs/random_selector.js b/test/unit/specs/random_selector.js index 91b0149b0..4fc46ca14 100644 --- a/test/unit/specs/random_selector.js +++ b/test/unit/specs/random_selector.js @@ -1,20 +1,21 @@ -describe('Random Selector', function () { +describe('Random Selector', function() { var randomSelector = require('../../../src/lib/selectors/random'); var _ = require('lodash'); var expect = require('expect.js'); - it('chooses a selection by random', function () { + it('chooses a selection by random', function() { var log = { a: 0, b: 0, c: 0 }; var choices = _.keys(log); - _.times(1000, function () { + _.times(1000, function() { var choice = randomSelector(choices); log[choice]++; }); - expect(_.filter(log, function (count) { - return count < 200 || count > 400; - })).to.have.length(0); - + expect( + _.filter(log, function(count) { + return count < 200 || count > 400; + }) + ).to.have.length(0); }); }); diff --git a/test/unit/specs/round_robin_selector.js b/test/unit/specs/round_robin_selector.js index 2298a0180..63645b14c 100644 --- a/test/unit/specs/round_robin_selector.js +++ b/test/unit/specs/round_robin_selector.js @@ -1,14 +1,14 @@ -describe('Round Robin Selector', function () { +describe('Round Robin Selector', function() { var selector = require('../../../src/lib/selectors/round_robin'); var _ = require('lodash'); var expect = require('expect.js'); - it('chooses options in order', function () { + it('chooses options in order', function() { var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; var expected = _.clone(options); var selections = []; - _.times(options.length, function () { + _.times(options.length, function() { selections.push(selector(options)); }); diff --git a/test/unit/specs/stdio_logger.js b/test/unit/specs/stdio_logger.js index 2ba49e4e1..15f7ad102 100644 --- a/test/unit/specs/stdio_logger.js +++ b/test/unit/specs/stdio_logger.js @@ -1,23 +1,22 @@ -describe('Stdio Logger', function () { - +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; - beforeEach(function () { + beforeEach(function() { parentLog = new Log(); }); - afterEach(function () { + afterEach(function() { parentLog.close(); }); function makeLogger(parent, levels) { parent = parent || parentLog; var config = { - levels: Log.parseLevels(levels || 'trace') + levels: Log.parseLevels(levels || 'trace'), }; return new StdioLogger(parent, config); } @@ -26,23 +25,23 @@ describe('Stdio Logger', function () { require('../generic_logger_tests')(makeLogger); - describe('colorizing', function () { + describe('colorizing', function() { var chalk = require('chalk'); var now = '2013-01-01T00:00:00Z'; var nowDate = new Date(now); var nowTime = nowDate.getTime(); - beforeEach(function () { + beforeEach(function() { stub.autoRelease(sinon.useFakeTimers(nowTime)); }); - it('uses colors when it\'s supported', function () { + it("uses colors when it's supported", function() { var logger = makeLogger(); var hasColor = require('chalk').supportsColor; expect(logger.color).to.be(hasColor); }); - it('obeys the logger.color === false', function () { + it('obeys the logger.color === false', function() { var logger = makeLogger(); stub(process.stdout, 'write'); var withoutColor = 'Elasticsearch INFO: ' + now + '\n something\n\n'; @@ -52,7 +51,7 @@ describe('Stdio Logger', function () { expect(process.stdout.write.lastCall.args[0]).to.eql(withoutColor); }); - it('obeys the logger.color === true', function () { + it('obeys the logger.color === true', function() { var logger = makeLogger(); stub(process.stdout, 'write'); @@ -61,8 +60,9 @@ describe('Stdio Logger', function () { logger.color = true; logger.onDebug('be weary'); expect(process.stdout.write.lastCall.args[0]).to.not.eql(withoutColor); - expect(chalk.stripColor(process.stdout.write.lastCall.args[0])).to.eql(withoutColor); + expect(chalk.stripColor(process.stdout.write.lastCall.args[0])).to.eql( + withoutColor + ); }); }); - }); diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index 734ef91e5..f41b47428 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -1,4 +1,4 @@ -describe('Stream Logger', function () { +describe('Stream Logger', function() { var Log = require('../../../src/lib/log'); var StreamLogger = require('../../../src/lib/loggers/stream'); var MockWritableStream = require('../../mocks/writable_stream'); @@ -11,14 +11,14 @@ describe('Stream Logger', function () { var stub = require('../../utils/auto_release_stub').make(); - beforeEach(function () { + beforeEach(function() { stub(stream, 'write'); stub(stream, 'end'); parentLog = new Log(); }); - afterEach(function () { + afterEach(function() { parentLog.close(); utils.clearWriteStreamBuffer(stream); }); @@ -27,34 +27,37 @@ describe('Stream Logger', function () { parent = parent || parentLog; var config = { levels: Log.parseLevels(levels || 'trace'), - stream: stream + stream: stream, }; return new StreamLogger(parent, config); } require('../generic_logger_tests')(makeLogger); - describe('buffer flush', function () { + describe('buffer flush', function() { if (require('stream').Writable) { - it('writes everything in the buffer to console.error', function () { + 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'; + var 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; + var exitHandler = _.isArray(exitHandlers) + ? _.last(exitHandlers) + : exitHandlers; // allow the logger to acctually write to the stream stream.write.restore(); // write the line 10 times - _.times(10, function () { + _.times(10, function() { logger.onDebug(line); }); // collect everything that is written to console.error var flushedOutput = ''; - stub(console, 'error', function (str) { + stub(console, 'error', function(str) { flushedOutput += str; }); @@ -69,9 +72,9 @@ describe('Stream Logger', function () { expect(flushedOutput.match(new RegExp(line, 'g'))).to.have.length(9); }); } else { - it('does not fall apart with non streams2 streams', function () { + it('does not fall apart with non streams2 streams', function() { var exitHandler; - stub(process, 'once', function (event, handler) { + stub(process, 'once', function(event, handler) { if (event === 'exit') { exitHandler = handler; } @@ -80,12 +83,11 @@ describe('Stream Logger', function () { makeLogger(); - expect(function () { + expect(function() { // call the event handler exitHandler.call(process); }).to.not.throwError(); }); } }); - }); diff --git a/test/unit/specs/tracer_logger.js b/test/unit/specs/tracer_logger.js index 28042670d..87d53c8c6 100644 --- a/test/unit/specs/tracer_logger.js +++ b/test/unit/specs/tracer_logger.js @@ -1,22 +1,21 @@ -describe('Tracer Logger', function () { - +describe('Tracer Logger', function() { var Log = require('../../../src/lib/log'); var TracerLogger = require('../../../src/lib/loggers/tracer'); var expect = require('expect.js'); var parentLog; - beforeEach(function () { + beforeEach(function() { parentLog = new Log(); }); - afterEach(function () { + afterEach(function() { parentLog.close(); }); function makeLogger(parent, levels) { parent = parent || parentLog; var config = { - levels: Log.parseLevels(levels || 'trace') + levels: Log.parseLevels(levels || 'trace'), }; return new TracerLogger(parent, config); } @@ -25,8 +24,8 @@ describe('Tracer Logger', function () { // require('../generic_logger_tests')(makeLogger); - describe('#formatTraceMessage', function () { - it('includes the original host', function () { + describe('#formatTraceMessage', function() { + it('includes the original host', function() { var logger = makeLogger(); var formatted = logger._formatTraceMessage({ @@ -34,37 +33,41 @@ describe('Tracer Logger', function () { url: 'https://originalHost.com:9522/path/to/thing?qs=100', body: '{ "yes": true }', status: 333, - response: '{ "ok": false }' + response: '{ "ok": false }', }); expect(formatted.curl).to.match(/-XDELETE/); - expect(formatted.curl).to.match(/https:\/\/originalHost\.com:9522\/?\s+/i); - expect(formatted.curl).to.match(/https:\/\/localhost:9200\/path\/to\/thing\?(pretty=true|qs=100|&){3}/); + expect(formatted.curl).to.match( + /https:\/\/originalHost\.com:9522\/?\s+/i + ); + expect(formatted.curl).to.match( + /https:\/\/localhost:9200\/path\/to\/thing\?(pretty=true|qs=100|&){3}/ + ); }); }); - describe('#write', function () { + describe('#write', function() { var logger; - beforeEach(function () { + beforeEach(function() { logger = makeLogger(); stub(logger.stream, 'write'); }); - it('detects tracer logs by listening messages wrapped in objects', function () { + it('detects tracer logs by listening messages wrapped in objects', function() { logger.write('TRACE', { msg: 'msgtext', curl: 'curlcall' }); expect(logger.stream.write.callCount).to.be(1); expect(logger.stream.write.lastCall.args[0]).to.contain('msgtext'); expect(logger.stream.write.lastCall.args[0]).to.contain('curlcall'); }); - it('comments everthing except the curl call', function () { + it('comments everthing except the curl call', function() { logger.write('TRACE', { msg: 'comment me', curl: 'no comment' }); expect(logger.stream.write.callCount).to.be(1); expect(logger.stream.write.lastCall.args[0]).to.match(/^# +comment me/m); expect(logger.stream.write.lastCall.args[0]).to.match(/^no comment/m); }); - it('just comments when it gets a string', function () { + it('just comments when it gets a string', function() { logger.write('TRACE', 'log me'); expect(logger.stream.write.callCount).to.be(1); expect(logger.stream.write.lastCall.args[0]).to.match(/^# +log me/m); diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index ae3af0de3..18de08229 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -14,7 +14,7 @@ var stub = require('../../utils/auto_release_stub').make(); * @param {Transport} tran - the transport to neuter */ function shortCircuitRequest(tran, delay) { - stub(tran.connectionPool, 'select', function (cb) { + stub(tran.connectionPool, 'select', function(cb) { setTimeout(cb, delay); }); } @@ -24,64 +24,65 @@ function getConnection(transport, status) { } function CustomConnectionPool() {} -CustomConnectionPool.prototype = Object.create(Transport.connectionPools.main.prototype); +CustomConnectionPool.prototype = Object.create( + Transport.connectionPools.main.prototype +); -describe('Transport Class', function () { - - describe('Constructor', function () { - it('Accepts a log class and intanciates it at this.log', function () { +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({ - log: CustomLogClass + log: CustomLogClass, }); expect(trans.log).to.be.a(CustomLogClass); }); - it('Accepts a connection pool class and intanciates it at this.connectionPool', function () { + it('Accepts a connection pool class and intanciates it at this.connectionPool', function() { var trans = new Transport({ - connectionPool: CustomConnectionPool + connectionPool: CustomConnectionPool, }); expect(trans.connectionPool).to.be.a(CustomConnectionPool); }); - it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () { + it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function() { Transport.connectionPools.custom = CustomConnectionPool; var trans = new Transport({ - connectionPool: 'custom' + connectionPool: 'custom', }); expect(trans.connectionPool).to.be.a(Transport.connectionPools.custom); delete Transport.connectionPools.custom; }); - it('Throws an error when connectionPool config is set wrong', function () { - expect(function () { + it('Throws an error when connectionPool config is set wrong', function() { + expect(function() { // eslint-disable-next-line no-new new Transport({ - connectionPool: 'pasta' + connectionPool: 'pasta', }); }).to.throwError(/invalid connectionpool/i); }); - it('calls sniff immediately if sniffOnStart is true', function () { + it('calls sniff immediately if sniffOnStart is true', function() { stub(Transport.prototype, 'sniff'); var trans = new Transport({ - sniffOnStart: true + sniffOnStart: true, }); expect(trans.sniff.callCount).to.eql(1); }); - it('schedules a sniff when sniffInterval is set', function () { + it('schedules a sniff when sniffInterval is set', function() { var clock = sinon.useFakeTimers('setTimeout'); stub.autoRelease(clock); stub(Transport.prototype, 'sniff'); var trans = new Transport({ - sniffInterval: 25000 + sniffInterval: 25000, }); expect(_.size(clock.timers)).to.eql(1); @@ -90,155 +91,147 @@ describe('Transport Class', function () { expect(trans.sniff.callCount).to.eql(1); expect(_.size(clock.timers)).to.eql(1); expect(clock.timers).to.not.have.key(id); - }); - describe('config.sniffedNodesProtocol', function () { - it('Assigns to itself', function () { + describe('config.sniffedNodesProtocol', function() { + it('Assigns to itself', function() { var football = {}; var trans = new Transport({ - sniffedNodesProtocol: football + sniffedNodesProtocol: football, }); expect(trans).to.have.property('sniffedNodesProtocol', football); }); - it('Defaults to null when no hosts given', function () { + it('Defaults to null when no hosts given', function() { var trans = new Transport({ - hosts: [] + hosts: [], }); expect(trans).to.have.property('sniffedNodesProtocol', null); }); - it('Defaults to "http" when a single http host given', function () { + it('Defaults to "http" when a single http host given', function() { var trans = new Transport({ hosts: [ new Host({ - protocol: 'http' - }) - ] + protocol: 'http', + }), + ], }); expect(trans).to.have.property('sniffedNodesProtocol', 'http'); }); - it('Defaults to "http" when multiple http host given', function () { + it('Defaults to "http" when multiple http host given', function() { var trans = new Transport({ hosts: [ new Host(), 'http://google.com', { host: 'foo', - path: 'bar' - } - ] + path: 'bar', + }, + ], }); expect(trans).to.have.property('sniffedNodesProtocol', 'http'); }); - it('Defaults to "https" when a single https host given', function () { + it('Defaults to "https" when a single https host given', function() { var trans = new Transport({ host: { - protocol: 'https' - } + protocol: 'https', + }, }); expect(trans).to.have.property('sniffedNodesProtocol', 'https'); }); - it('Defaults to "https" when every seed host uses https', function () { + it('Defaults to "https" when every seed host uses https', function() { var trans = new Transport({ hosts: [ 'https://localhost:9200', new Host({ - protocol: 'https' + protocol: 'https', }), { - protocol: 'https' - } - ] + protocol: 'https', + }, + ], }); expect(trans).to.have.property('sniffedNodesProtocol', 'https'); }); }); - describe('host config', function () { - it('rejects non-strings/objects', function () { - expect(function () { + describe('host config', function() { + it('rejects non-strings/objects', function() { + expect(function() { // eslint-disable-next-line no-new new Transport({ - host: [ - 'localhost', - 9393 - ] + host: ['localhost', 9393], }); }).to.throwError(TypeError); - expect(function () { + expect(function() { // eslint-disable-next-line no-new new Transport({ - host: [ - [9292] - ] + host: [[9292]], }); }).to.throwError(TypeError); }); - it('accepts the config value on the host: key', function () { + it('accepts the config value on the host: key', function() { stub(Transport.connectionPools.main.prototype, 'setHosts'); var trans = new Transport({ - host: 'localhost' + host: 'localhost', }); expect(trans.connectionPool.setHosts.callCount).to.eql(1); expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([ - new Host('localhost') + new Host('localhost'), ]); }); - it('accepts the config value on the hosts: key', function () { + it('accepts the config value on the hosts: key', function() { stub(Transport.connectionPools.main.prototype, 'setHosts'); var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); expect(trans.connectionPool.setHosts.callCount).to.eql(1); expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([ - new Host('localhost') + new Host('localhost'), ]); }); - it('accepts A host object as the config', 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({ - host: h + host: h, }); expect(trans.connectionPool.setHosts.callCount).to.eql(1); expect(trans.connectionPool.setHosts.lastCall.args[0][0]).to.be(h); }); - it('accepts strings as the config', function () { + it('accepts strings as the config', function() { stub(Transport.connectionPools.main.prototype, 'setHosts'); var trans = new Transport({ - hosts: [ - 'localhost:8888', - ] + hosts: ['localhost:8888'], }); expect(trans.connectionPool.setHosts.callCount).to.eql(1); expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([ new Host({ host: 'localhost', - port: 8888 - }) + port: 8888, + }), ]); }); - it('accepts objects as the config', function () { + it('accepts objects as the config', function() { stub(Transport.connectionPools.main.prototype, 'setHosts'); var trans = new Transport({ hosts: [ @@ -248,26 +241,26 @@ describe('Transport Class', function () { port: '777', path: '/bon/iver', query: { - access: 'all' - } - } - ] + access: 'all', + }, + }, + ], }); expect(trans.connectionPool.setHosts.callCount).to.eql(1); expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([ - new Host('https://myescluster.com:777/bon/iver?access=all') + new Host('https://myescluster.com:777/bon/iver?access=all'), ]); }); - it('passes the global config to the objects', function () { + it('passes the global config to the objects', function() { // since we can't mock out the Host constructor to see it's args, we will just // check that it's getting the suggestCompression setting stub(Transport.connectionPools.main.prototype, 'setHosts'); var trans = new Transport({ suggestCompression: true, - hosts: ['localhost:9200'] + hosts: ['localhost:9200'], }); expect(trans.connectionPool.setHosts).to.have.property('callCount', 1); @@ -276,7 +269,7 @@ describe('Transport Class', function () { expect(hosts[0]).to.have.property('suggestCompression', true); trans = new Transport({ - hosts: ['localhost:9200'] + hosts: ['localhost:9200'], }); expect(trans.connectionPool.setHosts).to.have.property('callCount', 2); @@ -286,24 +279,24 @@ describe('Transport Class', function () { }); }); - describe('randomizeHosts options', function () { - it('calls _.shuffle be default', function () { - stub(Transport.connectionPools.main.prototype, 'setHosts'); - stub(_, 'shuffle'); - // eslint-disable-next-line no-new - new Transport({ - hosts: 'localhost' - }); - - expect(_.shuffle.callCount).to.eql(1); - }); - it('skips the call to _.shuffle when false', function () { + describe('randomizeHosts options', function() { + it('calls _.shuffle be default', function() { stub(Transport.connectionPools.main.prototype, 'setHosts'); stub(_, 'shuffle'); // eslint-disable-next-line no-new new Transport({ hosts: 'localhost', - randomizeHosts: false + }); + + expect(_.shuffle.callCount).to.eql(1); + }); + it('skips the call to _.shuffle when false', function() { + stub(Transport.connectionPools.main.prototype, 'setHosts'); + stub(_, 'shuffle'); + // eslint-disable-next-line no-new + new Transport({ + hosts: 'localhost', + randomizeHosts: false, }); expect(_.shuffle.callCount).to.eql(0); @@ -311,8 +304,8 @@ describe('Transport Class', function () { }); }); - describe('#defer', function () { - it('returns a custom defer object', function () { + describe('#defer', function() { + it('returns a custom defer object', function() { var defer = Transport.prototype.defer(); expect(defer).to.have.property('promise'); expect(defer).to.have.property('resolve'); @@ -320,34 +313,37 @@ describe('Transport Class', function () { }); }); - - describe('#sniff', function () { + describe('#sniff', function() { var trans; - beforeEach(function () { + beforeEach(function() { trans = new Transport({ suggestCompression: true }); - stub(trans, 'request', function (params, cb) { - process.nextTick(function () { - cb(void 0, { - ok: true, - cluster_name: 'clustername', - nodes: nodeList - }, 200); + stub(trans, 'request', function(params, cb) { + process.nextTick(function() { + cb( + void 0, + { + ok: true, + cluster_name: 'clustername', + nodes: nodeList, + }, + 200 + ); }); }); stub(trans.connectionPool, 'setHosts'); }); - it('works without a callback', function (done) { + it('works without a callback', function(done) { trans.sniff(); - setTimeout(function () { + setTimeout(function() { expect(trans.request.callCount).to.eql(1); done(); }, 5); }); - it('calls the nodesToHostCallback with the list of nodes', function (done) { - trans.nodesToHostCallback = function (nodes) { + it('calls the nodesToHostCallback with the list of nodes', function(done) { + trans.nodesToHostCallback = function(nodes) { expect(nodes).to.eql(nodeList); done(); return []; @@ -355,19 +351,18 @@ describe('Transport Class', function () { trans.sniff(); }); - it('logs an error if nodes to host throws one', function (done) { - trans.nodesToHostCallback = function () { + it('logs an error if nodes to host throws one', function(done) { + trans.nodesToHostCallback = function() { throw new Error('I failed'); }; - trans.log.error = function () { + trans.log.error = function() { done(); }; trans.sniff(); }); - it('takes the host configs, converts them into Host objects, and passes them to connectionPool.setHosts', - function (done) { - trans.sniff(function () { + it('takes the host configs, converts them into Host objects, and passes them to connectionPool.setHosts', function(done) { + trans.sniff(function() { expect(trans.connectionPool.setHosts.callCount).to.eql(1); var hosts = trans.connectionPool.setHosts.lastCall.args[0]; @@ -384,10 +379,10 @@ describe('Transport Class', function () { }); }); - it('passes the global config to the objects', function (done) { + it('passes the global config to the objects', function(done) { // since we can't mock out the Host constructor to see it's args, we will just // check that it's getting the suggestCompression setting - trans.sniff(function () { + trans.sniff(function() { expect(trans.connectionPool.setHosts).to.have.property('callCount', 1); var hosts = trans.connectionPool.setHosts.lastCall.args[0]; expect(hosts).to.have.length(2); @@ -397,156 +392,165 @@ describe('Transport Class', function () { }); }); - it('passed back errors caught from the request', function (done) { - trans.request.func = function (params, cb) { - process.nextTick(function () { + it('passed back errors caught from the request', function(done) { + trans.request.func = function(params, cb) { + process.nextTick(function() { cb(new Error('something funked up')); }); }; - trans.sniff(function (err) { + trans.sniff(function(err) { expect(err.message).to.eql('something funked up'); done(); }); }); - it('passed back the full server response', function (done) { - trans.sniff(function (err, resp) { + it('passed back the full server response', function(done) { + trans.sniff(function(err, resp) { expect(resp.ok).to.eql(true); expect(resp.cluster_name).to.eql('clustername'); done(); }); }); - it('passed back the server response code', function (done) { - trans.sniff(function (err, resp, status) { + it('passed back the server response code', function(done) { + trans.sniff(function(err, resp, status) { expect(status).to.eql(200); done(); }); }); }); - describe('#request', function () { - it('logs when it begins', function (done) { + describe('#request', function() { + it('logs when it begins', function(done) { var trans = new Transport(); stub(trans.log, 'debug'); - stub(trans.connectionPool, 'select', function (cb) { + stub(trans.connectionPool, 'select', function(cb) { // simulate "no connections" process.nextTick(cb); }); - trans.request({}, function () { + trans.request({}, function() { expect(trans.log.debug.callCount).to.eql(1); done(); }); }); - it('rejects GET requests with a body (callback)', function (done) { + it('rejects GET requests with a body (callback)', function(done) { var trans = new Transport(); stub(trans.log, 'debug'); - stub(trans.connectionPool, 'select', function (cb) { + stub(trans.connectionPool, 'select', function(cb) { // simulate "no connections" process.nextTick(cb); }); - trans.request({ - body: 'JSON!!', - method: 'GET' - }, function (err) { - expect(err).to.be.a(TypeError); - expect(err.message).to.match(/body.*method.*get/i); - done(); - }); + trans.request( + { + body: 'JSON!!', + method: 'GET', + }, + function(err) { + expect(err).to.be.a(TypeError); + expect(err.message).to.match(/body.*method.*get/i); + done(); + } + ); }); - it('rejects GET requests with a body (promise)', function (done) { + it('rejects GET requests with a body (promise)', function(done) { var trans = new Transport(); stub(trans.log, 'debug'); - stub(trans.connectionPool, 'select', function (cb) { + stub(trans.connectionPool, 'select', function(cb) { // simulate "no connections" process.nextTick(cb); }); - trans.request({ - body: 'JSON!!', - method: 'GET' - }) - .then(function () { - done(new Error('expected the request to fail!')); - }, function (err) { - expect(err).to.be.a(TypeError); - expect(err.message).to.match(/body.*method.*get/i); - done(); - }); + trans + .request({ + body: 'JSON!!', + method: 'GET', + }) + .then( + function() { + done(new Error('expected the request to fail!')); + }, + function(err) { + expect(err).to.be.a(TypeError); + expect(err.message).to.match(/body.*method.*get/i); + done(); + } + ); }); - describe('gets a body', function () { - it('serializes it', function (done) { + describe('gets a body', function() { + it('serializes it', function(done) { var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); var conn = getConnection(trans); var body = { _id: 'simple body', - name: 'ഢധയമബ' + name: 'ഢധയമബ', }; - stub(conn, 'request', function (params) { - expect(params.headers).to.have.property('content-type', 'application/json'); + stub(conn, 'request', function(params) { + expect(params.headers).to.have.property( + 'content-type', + 'application/json' + ); expect(JSON.parse(params.body)).to.eql(body); done(); }); trans.request({ - body: body + body: body, }); }); - it('serializes bulk bodies', function (done) { + it('serializes bulk bodies', function(done) { var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); var conn = getConnection(trans); - var body = [ - { _id: 'simple body' }, - { name: 'ഢധയമബ' } - ]; + var body = [{ _id: 'simple body' }, { name: 'ഢധയമബ' }]; - stub(conn, 'request', function (params) { - expect(params.headers).to.have.property('content-type', 'application/x-ndjson'); + stub(conn, 'request', function(params) { + expect(params.headers).to.have.property( + 'content-type', + 'application/x-ndjson' + ); expect(params.body).to.eql( - '{"_id":"simple body"}\n' + - '{"name":"ഢധയമബ"}\n' + '{"_id":"simple body"}\n' + '{"name":"ഢധയമബ"}\n' ); done(); }); trans.request({ body: body, - bulkBody: true + bulkBody: true, }); }); }); - describe('gets a body it cant serialize', function () { - it('throws an error', function () { + describe('gets a body it cant serialize', function() { + it('throws an error', function() { var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); getConnection(trans); var body = { - _id: 'circular body' + _id: 'circular body', }; body.body = body; - expect(function () { + expect(function() { trans.request({ - body: body + body: body, }); }).to.throwError(TypeError); }); }); - describe('when selecting a connection', function () { - it('logs a warning, and responds with NoConnection when it receives nothing', function (done) { + describe('when selecting a connection', function() { + it('logs a warning, and responds with NoConnection when it receives nothing', function(done) { var trans = new Transport(); stub(trans.log, 'warning'); - trans.request({}, function (err, body, status) { + trans.request({}, function(err, body, status) { expect(trans.log.warning.callCount).to.eql(1); expect(err).to.be.a(errors.NoConnections); expect(body).to.be(undefined); @@ -554,78 +558,78 @@ describe('Transport Class', function () { done(); }); }); - it('quits if a sync selector throws an error', function () { + it('quits if a sync selector throws an error', function() { var trans = new Transport({ hosts: 'localhost', - selector: function () { + selector: function() { throw new Error('I am broken'); - } + }, }); - trans.request({}, function (err) { + trans.request({}, function(err) { expect(err.message).to.eql('I am broken'); }); }); - it('quits if gets an error from an async selector', function () { + it('quits if gets an error from an async selector', function() { var trans = new Transport({ hosts: 'localhost', - selector: function (connections, cb) { - process.nextTick(function () { + selector: function(connections, cb) { + process.nextTick(function() { cb(new Error('I am broken')); }); - } + }, }); - trans.request({}, function (err) { + trans.request({}, function(err) { expect(err.message).to.eql('I am broken'); }); }); - it('calls connection#request once it gets one', function (done) { + it('calls connection#request once it gets one', function(done) { var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); var conn = getConnection(trans); - stub(conn, 'request', function () { + stub(conn, 'request', function() { done(); }); - trans.request({}, function () {}); + trans.request({}, function() {}); }); }); - describe('gets a connection err', function () { + describe('gets a connection err', function() { // create a test that checks N retries function testRetries(retries) { - return function (done) { + return function(done) { var randomSelector = require('../../../src/lib/selectors/random'); var connections; var attempts = 0; function failRequest(params, cb) { attempts++; - process.nextTick(function () { + process.nextTick(function() { cb(new Error('Unable to do that thing you wanted')); }); } var trans = new Transport({ - hosts: _.map(new Array(retries + 1), function (val, i) { + hosts: _.map(new Array(retries + 1), function(val, i) { return 'localhost/' + i; }), maxRetries: retries, - selector: function (_conns) { + selector: function(_conns) { connections = _conns; return randomSelector(_conns); - } + }, }); // trigger a select so that we can harvest the connection list trans.connectionPool.select(_.noop); - _.each(connections, function (conn) { + _.each(connections, function(conn) { stub(conn, 'request', failRequest); }); - trans.request({}, function (err, resp, body) { + trans.request({}, function(err, resp, body) { expect(attempts).to.eql(retries + 1); expect(err).to.be.a(errors.ConnectionFault); expect(resp).to.be(undefined); @@ -635,20 +639,22 @@ describe('Transport Class', function () { }); }; } - it('retries when there are retries remaining', testRetries(_.random(25, 40))); + it( + 'retries when there are retries remaining', + testRetries(_.random(25, 40)) + ); it('responds when there are no retries', testRetries(0)); }); - - describe('return value', function () { - it('returns an object with an abort() method when a callback is sent', function () { + describe('return value', function() { + it('returns an object with an abort() method when a callback is sent', function() { var tran = new Transport(); shortCircuitRequest(tran); var 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 () { + it('the object is a promise when a callback is not suplied', function() { var tran = new Transport(); shortCircuitRequest(tran); var ret = tran.request({}); @@ -656,17 +662,17 @@ describe('Transport Class', 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 () { + it('promise is always pulled from the defer created by this.defer()', function() { var fakePromise = {}; var origDefer = Transport.prototype.defer; var tran = new Transport({ - defer: function () { + defer: function() { return { resolve: _.noop, reject: _.noop, - promise: fakePromise + promise: fakePromise, }; - } + }, }); shortCircuitRequest(tran); var ret = tran.request({}); @@ -676,26 +682,26 @@ describe('Transport Class', function () { }); }); - describe('handles process.domain', function () { + describe('handles process.domain', function() { if (process && process.hasOwnProperty('domain')) { - it('works without a domain', function () { + it('works without a domain', function() { expect(process.domain).to.be(null); var tran = new Transport(); shortCircuitRequest(tran); - tran.request({}, function () { + tran.request({}, function() { expect(process.domain).to.be(null); }); }); - it('binds the callback to the correct domain', function () { + it('binds the callback to the correct domain', function() { expect(process.domain).to.be(null); var domain = require('domain').create(); - domain.run(function () { + domain.run(function() { var tran = new Transport(); shortCircuitRequest(tran); expect(process.domain).not.to.be(null); - var startingDomain = process.domain - tran.request({}, function () { + var startingDomain = process.domain; + tran.request({}, function() { expect(process.domain).not.to.be(null); expect(process.domain).to.be(startingDomain); process.domain.exit(); @@ -705,48 +711,48 @@ describe('Transport Class', function () { } }); - describe('aborting', function () { - it('prevents the request from starting if called in the same tick', function () { + describe('aborting', function() { + it('prevents the request from starting if called in the same tick', function() { var tran = new Transport({ - host: 'localhost' + host: 'localhost', }); var con = getConnection(tran); - stub(con, 'request', function () { + stub(con, 'request', function() { throw new Error('Request should not have been called.'); }); var ret = tran.request({}); ret.abort(); }); - it('calls the function returned by the connector if it has been called', function (done) { + it('calls the function returned by the connector if it has been called', function(done) { var tran = new Transport({ - host: 'localhost' + host: 'localhost', }); var con = getConnection(tran); - stub(con, 'request', function () { - process.nextTick(function () { + stub(con, 'request', function() { + process.nextTick(function() { ret.abort(); }); - return function () { + return function() { done(); }; }); var ret = tran.request({}); }); - it('ignores the response from the connection when the connector does not support aborting', function (done) { + it('ignores the response from the connection when the connector does not support aborting', function(done) { var tran = new Transport({ - host: 'localhost' + host: 'localhost', }); var con = getConnection(tran); - stub(con, 'request', function (params, cb) { + stub(con, 'request', function(params, cb) { cb(); }); - var ret = tran.request({}, function () { + var ret = tran.request({}, function() { throw new Error('Callback should not have been called.'); }); ret.abort(); @@ -754,8 +760,8 @@ describe('Transport Class', function () { }); }); - describe('timeout', function () { - it('uses 30 seconds for the default', function () { + describe('timeout', function() { + it('uses 30 seconds for the default', function() { var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var tran = new Transport({}); @@ -765,16 +771,16 @@ describe('Transport Class', function () { prom.then(_.noop, _.noop); expect(_.size(clock.timers)).to.eql(1); - _.each(clock.timers, function (timer, id) { + _.each(clock.timers, function(timer, id) { expect(timer.callAt).to.eql(30000); clearTimeout(id); }); }); - it('inherits the requestTimeout from the transport', function () { + it('inherits the requestTimeout from the transport', function() { var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var tran = new Transport({ - requestTimeout: 5000 + requestTimeout: 5000, }); var prom = tran.request({}); @@ -782,45 +788,47 @@ describe('Transport Class', function () { prom.then(_.noop, _.noop); expect(_.size(clock.timers)).to.eql(1); - _.each(clock.timers, function (timer, id) { + _.each(clock.timers, function(timer, id) { expect(timer.callAt).to.eql(5000); clearTimeout(id); }); }); - it('inherits the pingTimeout from the transport', function () { + it('inherits the pingTimeout from the transport', function() { var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var tran = new Transport({ requestTimeout: 4000, - pingTimeout: 5000 + pingTimeout: 5000, }); var prom = tran.request({ path: '/', - method: 'HEAD' + method: 'HEAD', }); // disregard promise, prevent bluebird's warnings prom.then(_.noop, _.noop); expect(_.size(clock.timers)).to.eql(1); - _.each(clock.timers, function (timer, id) { + _.each(clock.timers, function(timer, id) { expect(timer.callAt).to.eql(5000); clearTimeout(id); }); }); - - _.each([false, 0, null], function (falsy) { - it('skips the timeout when it is ' + falsy, function () { + _.each([false, 0, null], function(falsy) { + it('skips the timeout when it is ' + falsy, function() { var clock = sinon.useFakeTimers(); stub.autoRelease(clock); var tran = new Transport({}); - stub(tran.connectionPool, 'select', function () {}); + stub(tran.connectionPool, 'select', function() {}); - tran.request({ - requestTimeout: falsy - }, function () {}); + tran.request( + { + requestTimeout: falsy, + }, + function() {} + ); expect(_.size(clock.timers)).to.eql(0); }); @@ -828,20 +836,20 @@ describe('Transport Class', function () { }); }); - describe('#setHosts', function () { - it('accepts strings, host objects, and host configs', function () { - + describe('#setHosts', function() { + it('accepts strings, host objects, and host configs', function() { var trans = new Transport({ suggestCompression: true }); stub(trans.connectionPool, 'setHosts'); trans.setHosts([ { host: 'first.server', port: 9200 }, 'http://second.server:9200', - new Host('http://third.server:9200') + new Host('http://third.server:9200'), ]); sinon.assert.calledOnce(trans.connectionPool.setHosts); - var host, hosts = trans.connectionPool.setHosts.firstCall.args[0]; + var host; + var hosts = trans.connectionPool.setHosts.firstCall.args[0]; expect(hosts).to.have.length(3); @@ -865,8 +873,8 @@ describe('Transport Class', function () { }); }); - describe('#close', function () { - it('proxies the call to it\'s log and connection pool', function () { + describe('#close', function() { + it("proxies the call to it's log and connection pool", function() { var tran = new Transport(); stub(tran.connectionPool, 'close'); stub(tran.log, 'close'); @@ -877,5 +885,4 @@ describe('Transport Class', function () { expect(tran.log.close.callCount).to.eql(1); }); }); - }); diff --git a/test/unit/specs/transport_with_server.js b/test/unit/specs/transport_with_server.js index 1a61ab72e..96b0a1763 100644 --- a/test/unit/specs/transport_with_server.js +++ b/test/unit/specs/transport_with_server.js @@ -9,12 +9,12 @@ var through2 = require('through2'); var _ = require('lodash'); var stub = require('../../utils/auto_release_stub').make(); -describe('Transport + Mock server', function () { - describe('#request', function () { - describe('server responds', function () { +describe('Transport + Mock server', function() { + describe('#request', function() { + describe('server responds', function() { var serverMock; - before(function () { + before(function() { serverMock = nock('http://localhost') .get('/give-me-400') .reply(400, 'sorry bub') @@ -28,235 +28,266 @@ describe('Transport + Mock server', function () { .get('/exists?') .reply(200, { - status: 200 + status: 200, }) .get('/give-me-someth') .reply(200, '{"not":"valid', { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }) .get('/') .reply(200, { - 'the answer': 42 + 'the answer': 42, }) .get('/huh?') .reply(530, 'boo') .get('/hottie-threads') - .reply(200, [ - 'he said', - 'she said', - 'he said', - 'she said', - 'he said', - 'she said' - ].join('\n'), { - 'Content-Type': 'text/plain' - }); + .reply( + 200, + [ + 'he said', + 'she said', + 'he said', + 'she said', + 'he said', + 'she said', + ].join('\n'), + { + 'Content-Type': 'text/plain', + } + ); }); - after(function () { + after(function() { serverMock.done(); }); - describe('with a 400 status code', function () { - it('passes back a 400/BadRequest error', function (done) { + describe('with a 400 status code', function() { + it('passes back a 400/BadRequest error', function(done) { var trans = new Transport({ - hosts: 'localhost' + hosts: 'localhost', }); - trans.request({ - path: '/give-me-400' - }, function (err, body, status) { - expect(err).to.be.a(errors[400]); - expect(err).to.be.a(errors.BadRequest); - expect(body).to.eql('sorry bub'); - expect(status).to.eql(400); - done(); + trans.request( + { + path: '/give-me-400', + }, + function(err, body, status) { + expect(err).to.be.a(errors[400]); + expect(err).to.be.a(errors.BadRequest); + expect(body).to.eql('sorry bub'); + expect(status).to.eql(400); + done(); + } + ); + }); + }); + + describe('with a 404 status code', function() { + describe('and castExists is set', function() { + it('sends back false', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/give-me-404', + castExists: true, + }, + function(err, body, status) { + expect(err).to.be(undefined); + expect(body).to.eql(false); + expect(status).to.eql(404); + done(); + } + ); + }); + }); + describe('and the castExists param is not set', function() { + it('sends back a 404/NotFound error', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/give-me-404', + }, + function(err, body, status) { + expect(err).to.be.a(errors[404]); + expect(err).to.be.a(errors.NotFound); + expect(body).to.eql('nothing here'); + expect(status).to.eql(404); + done(); + } + ); }); }); }); - describe('with a 404 status code', function () { - describe('and castExists is set', function () { - it('sends back false', function (done) { + describe('with a 500 status code', function() { + it('passes back a 500/InternalServerError error', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/give-me-500', + }, + function(err, body, status) { + expect(err).to.be.a(errors[500]); + expect(err).to.be.a(errors.InternalServerError); + expect(body).to.eql('ah shit'); + expect(status).to.eql(500); + done(); + } + ); + }); + }); + + describe('with a 530 status code', function() { + it('passes back a Generic error', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/huh?', + }, + function(err, body, status) { + expect(err).to.be.a(errors.Generic); + expect(body).to.eql('boo'); + expect(status).to.eql(530); + done(); + } + ); + }); + }); + + 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({ - hosts: 'localhost' + hosts: 'localhost', }); - trans.request({ - path: '/give-me-404', - castExists: true - }, function (err, body, status) { + trans.request( + { + path: '/exists?', + castExists: true, + }, + function(err, body, status) { + expect(err).to.be(undefined); + expect(body).to.eql(true); + expect(status).to.eql(200); + done(); + } + ); + }); + }); + describe('with a partial response body', function() { + it('sends back a serialization error', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/give-me-someth', + }, + function(err, body, status) { + expect(err).to.be.a(errors.Serialization); + expect(body).to.eql('{"not":"valid'); + expect(status).to.eql(200); + done(); + } + ); + }); + }); + describe('with a valid response body', function() { + it('sends back the body and status code with no error', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/', + }, + function(err, body) { + expect(err).to.be(undefined); + expect(body).to.eql({ + 'the answer': 42, + }); + done(); + } + ); + }); + }); + }); + + describe('with plain text', function() { + it('notices the content-type header and returns the text', function(done) { + var trans = new Transport({ + hosts: 'localhost', + }); + + trans.request( + { + path: '/hottie-threads', + }, + function(err, body) { expect(err).to.be(undefined); - expect(body).to.eql(false); - expect(status).to.eql(404); + expect(body).to.match(/s?he said/g); done(); - }); - }); - }); - describe('and the castExists param is not set', function () { - it('sends back a 404/NotFound error', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/give-me-404' - }, function (err, body, status) { - expect(err).to.be.a(errors[404]); - expect(err).to.be.a(errors.NotFound); - expect(body).to.eql('nothing here'); - expect(status).to.eql(404); - done(); - }); - }); - }); - }); - - describe('with a 500 status code', function () { - it('passes back a 500/InternalServerError error', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/give-me-500' - }, function (err, body, status) { - expect(err).to.be.a(errors[500]); - expect(err).to.be.a(errors.InternalServerError); - expect(body).to.eql('ah shit'); - expect(status).to.eql(500); - done(); - }); - }); - }); - - describe('with a 530 status code', function () { - it('passes back a Generic error', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/huh?' - }, function (err, body, status) { - expect(err).to.be.a(errors.Generic); - expect(body).to.eql('boo'); - expect(status).to.eql(530); - done(); - }); - }); - }); - - 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({ - hosts: 'localhost' - }); - - trans.request({ - path: '/exists?', - castExists: true - }, function (err, body, status) { - expect(err).to.be(undefined); - expect(body).to.eql(true); - expect(status).to.eql(200); - done(); - }); - }); - }); - describe('with a partial response body', function () { - it('sends back a serialization error', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/give-me-someth', - }, function (err, body, status) { - expect(err).to.be.a(errors.Serialization); - expect(body).to.eql('{"not":"valid'); - expect(status).to.eql(200); - done(); - }); - }); - }); - describe('with a valid response body', function () { - it('sends back the body and status code with no error', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/', - }, function (err, body) { - expect(err).to.be(undefined); - expect(body).to.eql({ - 'the answer': 42 - }); - done(); - }); - }); - }); - }); - - describe('with plain text', function () { - it('notices the content-type header and returns the text', function (done) { - var trans = new Transport({ - hosts: 'localhost' - }); - - trans.request({ - path: '/hottie-threads', - }, function (err, body) { - expect(err).to.be(undefined); - expect(body).to.match(/s?he said/g); - done(); - }); + } + ); }); }); }); - describe('return value', function () { - it('resolves the promise it with the response body', function (done) { + describe('return value', function() { + it('resolves the promise it with the response body', function(done) { nock('http://esbox.1.com') .get('/') .reply(200, { - good: 'day' + good: 'day', }); var tran = new Transport({ - hosts: 'http://esbox.1.com' + hosts: 'http://esbox.1.com', }); - tran.request({}).then(function (resp) { + tran.request({}).then(function(resp) { expect(resp).to.eql({ - good: 'day' + good: 'day', }); done(); }, done); }); }); - describe('timeout', function () { - it('clears the timeout when the request is complete', function () { + describe('timeout', function() { + it('clears the timeout when the request is complete', function() { var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); stub.autoRelease(clock); var tran = new Transport({ - host: 'http://localhost:9200' + host: 'http://localhost:9200', }); nock('http://localhost:9200') .get('/') .reply(200, { - i: 'am here' + i: 'am here', }); - tran.request({}, function (err, resp, status) { + tran.request({}, function(err, resp, status) { expect(err).to.be(undefined); expect(resp).to.eql({ i: 'am here' }); expect(status).to.eql(200); @@ -265,44 +296,47 @@ describe('Transport + Mock server', function () { }); }); - it('timeout responds with a requestTimeout error', function (done) { + it('timeout responds with a requestTimeout error', function(done) { var tran = new Transport({ - host: 'http://localhost:9200' + host: 'http://localhost:9200', }); nock('http://localhost:9200') .get('/') .delay(1000) .reply(200, { - i: 'am here' + i: 'am here', }); - tran.request({ - requestTimeout: 25 - }, function (err) { - expect(err).to.be.a(errors.RequestTimeout); - done(); - }); + tran.request( + { + requestTimeout: 25, + }, + function(err) { + expect(err).to.be.a(errors.RequestTimeout); + done(); + } + ); }); }); - describe('sniffOnConnectionFault', function () { - it('schedules a sniff when sniffOnConnectionFault is set and a connection failes', function () { + describe('sniffOnConnectionFault', function() { + it('schedules a sniff when sniffOnConnectionFault is set and a connection failes', function() { var clock = sinon.useFakeTimers('setTimeout'); stub.autoRelease(clock); nock('http://esbox.1.com') .get('/') - .reply(200, function () { - var str = through2(function (chunk, enc, cb) { + .reply(200, function() { + var str = through2(function(chunk, enc, cb) { cb(new Error('force error')); }); - setTimeout(function () { + setTimeout(function() { str.write(''); }, 10); - str.setEncoding = function () {}; // force nock's isStream detection + str.setEncoding = function() {}; // force nock's isStream detection return str; }); @@ -311,26 +345,31 @@ describe('Transport + Mock server', function () { var tran = new Transport({ hosts: 'http://esbox.1.com', sniffOnConnectionFault: true, - maxRetries: 0 + maxRetries: 0, }); - expect(tran.connectionPool._onConnectionDied).to.not.be(ConnectionPool.prototype._onConnectionDied); + expect(tran.connectionPool._onConnectionDied).to.not.be( + ConnectionPool.prototype._onConnectionDied + ); - tran.request({ - requestTimeout: Infinity - }) - .then(function () { - throw new Error('expected the request to fail'); - }) - .catch(function () { - expect(ConnectionPool.prototype._onConnectionDied.callCount).to.eql(1); - expect(tran.sniff.callCount).to.eql(0); - expect(_.size(clock.timers)).to.eql(1); + tran + .request({ + requestTimeout: Infinity, + }) + .then(function() { + throw new Error('expected the request to fail'); + }) + .catch(function() { + expect(ConnectionPool.prototype._onConnectionDied.callCount).to.eql( + 1 + ); + expect(tran.sniff.callCount).to.eql(0); + expect(_.size(clock.timers)).to.eql(1); - var timeout = _.values(clock.timers).pop(); - timeout.func(); - expect(tran.sniff.callCount).to.eql(1); - }); + var timeout = _.values(clock.timers).pop(); + timeout.func(); + expect(tran.sniff.callCount).to.eql(1); + }); }); }); }); diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index 27ad16cff..05eb90dea 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -4,28 +4,27 @@ var expect = require('expect.js'); var stub = require('../../utils/auto_release_stub').make(); -describe('Utils', function () { - - describe('Additional Type Checkers', function () { - describe('#isArrayOfStrings', function () { +describe('Utils', function() { + describe('Additional Type Checkers', function() { + describe('#isArrayOfStrings', function() { const thing = { is: ['creamy', 'poop'], - not: {} + not: {}, }; - it('likes arrays of strings', function () { + it('likes arrays of strings', function() { expect(utils.isArrayOfStrings(thing.is)).to.be(true); }); - it('dislikes when there is even one non string', function () { + it('dislikes when there is even one non string', function() { // notice a string in the array thing.is.push(thing.not || ' not '); expect(utils.isArrayOfStrings(thing.is)).to.be(false); }); }); - describe('#isNumeric', function () { - it('likes integer literals', function () { + describe('#isNumeric', function() { + it('likes integer literals', function() { expect(utils.isNumeric('-10')).to.be(true); expect(utils.isNumeric('0')).to.be(true); expect(utils.isNumeric('5')).to.be(true); @@ -34,10 +33,10 @@ describe('Utils', function () { expect(utils.isNumeric(32)).to.be(true); expect(utils.isNumeric('040')).to.be(true); expect(utils.isNumeric('0xFF')).to.be(true); - expect(utils.isNumeric(0xFFF)).to.be(true); + expect(utils.isNumeric(0xfff)).to.be(true); }); - it('likes float literals', function () { + it('likes float literals', function() { expect(utils.isNumeric('-1.6')).to.be(true); expect(utils.isNumeric('4.536')).to.be(true); expect(utils.isNumeric(-2.6)).to.be(true); @@ -46,7 +45,7 @@ describe('Utils', function () { expect(utils.isNumeric('123e-2')).to.be(true); }); - it('dislikes non-numeric stuff', function () { + it('dislikes non-numeric stuff', function() { expect(utils.isNumeric('')).to.be(false); expect(utils.isNumeric(' ')).to.be(false); expect(utils.isNumeric('\t\t')).to.be(false); @@ -66,219 +65,238 @@ describe('Utils', function () { expect(utils.isNumeric([])).to.be(false); expect(utils.isNumeric([1, 2, 3, 4])).to.be(false); expect(utils.isNumeric({})).to.be(false); - expect(utils.isNumeric(function () {})).to.be(false); + expect(utils.isNumeric(function() {})).to.be(false); }); }); + describe('#isInterval', function() { + _.forEach( + { + M: 'months', + w: 'weeks', + d: 'days', + h: 'hours', + m: 'minutes', + s: 'seconds', + y: 'years', + }, + function(name, unit) { + it('likes ' + name, function() { + expect(utils.isInterval('1' + unit)).to.be(true); + }); - describe('#isInterval', function () { - _.forEach({ - M: 'months', - w: 'weeks', - d: 'days', - h: 'hours', - m: 'minutes', - s: 'seconds', - y: 'years' - }, - function (name, unit) { - it('likes ' + name, function () { - expect(utils.isInterval('1' + unit)).to.be(true); - }); + it('likes decimal ' + name, function() { + expect(utils.isInterval('1.5' + unit)).to.be(true); + }); + } + ); - it('likes decimal ' + name, function () { - expect(utils.isInterval('1.5' + unit)).to.be(true); - }); - }); - - it('dislikes more than one unit', function () { + it('dislikes more than one unit', function() { expect(utils.isInterval('1my')).to.be(false); }); - it('dislikes spaces', function () { + it('dislikes spaces', function() { expect(utils.isInterval('1 m')).to.be(false); }); }); }); - - describe('String Transformers', function () { - - describe('#camelCase', function () { - it('find spaces, underscores, and other natural word breaks', function () { - expect(utils.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); + describe('String Transformers', function() { + describe('#camelCase', function() { + it('find spaces, underscores, and other natural word breaks', function() { + expect(utils.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql( + 'neilPatrickHarrisIsADog' + ); }); - it('ignores abreviations', function () { + it('ignores abreviations', function() { expect(utils.camelCase('Json_parser')).to.eql('jsonParser'); }); - it('handles leading _', function () { + it('handles leading _', function() { expect(utils.camelCase('_thing_one_')).to.eql('_thingOne'); }); - it('works on numbers', function () { + it('works on numbers', function() { expect(utils.camelCase('version 1.0')).to.eql('version10'); }); }); - describe('#studlyCase', function () { - it('find spaces, underscores, and other natural word breaks', function () { - expect(utils.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); + describe('#studlyCase', function() { + it('find spaces, underscores, and other natural word breaks', function() { + expect(utils.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql( + 'NeilPatrickHarrisIsADog' + ); }); - it('ignores abreviations', function () { + it('ignores abreviations', function() { expect(utils.studlyCase('Json_parser')).to.eql('JsonParser'); }); - it('handles leading _', function () { + it('handles leading _', function() { expect(utils.studlyCase('_thing_one_')).to.eql('_ThingOne'); }); - it('works on numbers', function () { + it('works on numbers', function() { expect(utils.studlyCase('version 1.0')).to.eql('Version10'); }); }); - describe('#snakeCase', function () { - it('find spaces, underscores, and other natural word breaks', function () { - expect(utils.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); + describe('#snakeCase', function() { + it('find spaces, underscores, and other natural word breaks', function() { + expect(utils.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql( + 'neil_patrick_harris_is_a_dog' + ); }); - it('ignores abreviations', function () { + it('ignores abreviations', function() { expect(utils.snakeCase('Json_parser')).to.eql('json_parser'); }); - it('handles leading _', function () { + it('handles leading _', function() { expect(utils.snakeCase('_thing_one_')).to.eql('_thing_one'); }); - it('works on numbers', function () { + it('works on numbers', function() { expect(utils.snakeCase('version 1.0')).to.eql('version_1_0'); }); }); - describe('#toUpperString', function () { - it('transforms normal strings', function () { + describe('#toUpperString', function() { + it('transforms normal strings', function() { expect(utils.toUpperString('PASTA')).to.eql('PASTA'); }); - it('ignores long form empty vals (null, false, undef)', function () { + it('ignores long form empty vals (null, false, undef)', function() { expect(utils.toUpperString(null)).to.eql(''); expect(utils.toUpperString(false)).to.eql(''); expect(utils.toUpperString(void 0)).to.eql(''); }); - it('uses the objects own toString', function () { + it('uses the objects own toString', function() { expect(utils.toUpperString(['A', 'B'])).to.eql('A,B'); }); - it('sorta kinda works on objects', function () { + it('sorta kinda works on objects', function() { expect(utils.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); }); }); - describe('#repeat', function () { - it('repeats strings', function () { + describe('#repeat', function() { + it('repeats strings', function() { expect(utils.repeat(' ', 5)).to.eql(' '); expect(utils.repeat('foobar', 2)).to.eql('foobarfoobar'); }); }); - describe('#ucfirst', function () { - it('only capitalized the first letter, lowercases everything else', function () { + describe('#ucfirst', function() { + it('only capitalized the first letter, lowercases everything else', function() { expect(utils.ucfirst('ALGER')).to.eql('Alger'); }); }); - }); - describe('#createArray', function () { - it('accepts an array of things and simply returns a copy of it', 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 = utils.createArray(inp); expect(out).to.eql(inp); expect(out).to.not.be(inp); }); - it('accepts a primitive value and calls the the transform function', function (done) { - utils.createArray('str', function (val) { + it('accepts a primitive value and calls the the transform function', function(done) { + utils.createArray('str', function(val) { expect(val).to.be('str'); done(); }); }); - it('wraps any non-array in an array', function () { + it('wraps any non-array in an array', function() { expect(utils.createArray({})).to.eql([{}]); expect(utils.createArray('')).to.eql(['']); expect(utils.createArray(123)).to.eql([123]); expect(utils.createArray(/abc/)).to.eql([/abc/]); expect(utils.createArray(false)).to.eql([false]); }); - it('returns false when the transform function returns undefined', function () { - expect(utils.createArray(['str', 1], function (val) { - if (_.isString(val)) { - return { - val: val - }; - } - })).to.be(false); + it('returns false when the transform function returns undefined', function() { + expect( + utils.createArray(['str', 1], function(val) { + if (_.isString(val)) { + return { + val: val, + }; + } + }) + ).to.be(false); }); }); - describe('#funcEnum', function () { + describe('#funcEnum', function() { /* * _.funcEnum(object, key, opts, default); */ - it('tests if the value at key in object is a function, returns it if so', function () { + it('tests if the value at key in object is a function, returns it if so', function() { var config = { - func: function () {} + func: function() {}, }; - expect(utils.funcEnum(config, 'func', {}, 'toString')) - .to.be(config.func); + expect(utils.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 () { + it('tests if the value at key in object is undefined, returns the option at key default if so', function() { var config = { - func: undefined + func: undefined, }; - expect(utils.funcEnum(config, 'func', {}, 'toString')) - .to.be(Object.prototype.toString); + expect(utils.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 () { + it('tests if the value at key in object is a string, returns the option at that key if so', function() { var config = { - 'config key name': 'toString' + 'config key name': 'toString', }; - expect(utils.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) - .to.be('pizza'); + expect( + utils.funcEnum( + config, + 'config key name', + { toString: 'pizza' }, + 'toJSON' + ) + ).to.be('pizza'); }); - it('throws an informative error if the selection if invalid', function () { + it('throws an informative error if the selection if invalid', function() { var config = { - 'config': 'val' + config: 'val', }; - expect(function () { + expect(function() { utils.funcEnum(config, 'config', {}); }).to.throwError(/expected a function/i); - expect(function () { + expect(function() { utils.funcEnum(config, 'config', { main: 'default' }, 'main'); }).to.throwError(/expected a function or main/i); - expect(function () { - utils.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); + expect(function() { + utils.funcEnum( + config, + 'config', + { main: 'default', other: 'default' }, + 'main' + ); }).to.throwError(/expected a function or one of main, other/i); }); }); - describe('#applyArgs', function () { - _.times(10, function (i) { + describe('#applyArgs', function() { + _.times(10, function(i) { var method = i > 5 ? 'apply' : 'call'; var argCount = i + 1; var slice = 1; - it('uses ' + method + ' with ' + i + ' args', function () { - var func = function () {}; + it('uses ' + method + ' with ' + i + ' args', function() { + var func = function() {}; stub(func, method); - var args = _.map(new Array(i), function (val, i) { return i; }); + var args = _.map(new Array(i), function(val, i) { + return i; + }); utils.applyArgs(func, null, args); expect(func[method].callCount).to.eql(1); @@ -289,27 +307,36 @@ describe('Utils', function () { } }); - it('slices the arguments properly before calling ' + method + ' with ' + argCount + ' args sliced at ' + slice, - function () { - var func = function () {}; - stub(func, method); + it( + 'slices the arguments properly before calling ' + + method + + ' with ' + + argCount + + ' args sliced at ' + + slice, + function() { + var func = function() {}; + stub(func, method); - var args = _.map(new Array(argCount), function (val, i) { return i; }); - var expected = args.slice(slice); - utils.applyArgs(func, null, args, slice); + var args = _.map(new Array(argCount), function(val, i) { + return i; + }); + var expected = args.slice(slice); + utils.applyArgs(func, null, args, slice); - expect(func[method].callCount).to.eql(1); - if (method === 'apply') { - expect(func.apply.lastCall.args[1]).to.eql(expected); - } else { - expect(func.call.lastCall.args.splice(1)).to.eql(expected); + expect(func[method].callCount).to.eql(1); + if (method === 'apply') { + expect(func.apply.lastCall.args[1]).to.eql(expected); + } else { + expect(func.call.lastCall.args.splice(1)).to.eql(expected); + } } - }); + ); }); }); - describe('#getUnwrittenFromStream', function () { - it('ignores things that do not have writableState', function () { + describe('#getUnwrittenFromStream', function() { + it('ignores things that do not have writableState', function() { expect(utils.getUnwrittenFromStream()).to.be(undefined); expect(utils.getUnwrittenFromStream(false)).to.be(undefined); expect(utils.getUnwrittenFromStream([])).to.be(undefined); @@ -318,12 +345,12 @@ describe('Utils', function () { if (require('stream').Writable) { var MockWritableStream = require('../../mocks/writable_stream'); - it('ignores empty stream', function () { + it('ignores empty stream', function() { var stream = new MockWritableStream(); expect(utils.getUnwrittenFromStream(stream)).to.be(''); }); - it('returns only what is in the buffer', function () { + it('returns only what is in the buffer', function() { var stream = new MockWritableStream(); stream.write('hot'); stream.write('dog'); @@ -331,5 +358,4 @@ describe('Utils', function () { }); } }); - }); diff --git a/test/unit/specs/yaml_test_reader.js b/test/unit/specs/yaml_test_reader.js index 4e101c1df..938dc3bd9 100644 --- a/test/unit/specs/yaml_test_reader.js +++ b/test/unit/specs/yaml_test_reader.js @@ -1,16 +1,16 @@ -describe('Yaml Test Reader', function () { +describe('Yaml Test Reader', function() { var YamlDoc = require('../../integration/yaml_suite/yaml_doc'); var compare = YamlDoc.compareRangeToVersion; var expect = require('expect.js'); - describe('version range comparison', function () { - it('supports unbounded ranges', function () { + describe('version range comparison', function() { + it('supports unbounded ranges', function() { expect(compare(' - ', '999999999999999999')).to.be(true); expect(compare('0 - ', '999999999999999999')).to.be(true); expect(compare(' - 1', '999999999999999999')).to.be(false); }); - it('supports bound ranges', function () { + it('supports bound ranges', function() { expect(compare('1.4 - 1.5', '1.4.4')).to.be(true); expect(compare('1.4.4 - 1.5', '1.4.4')).to.be(true); expect(compare('1.4 - 1.4.4', '1.4.4')).to.be(true); diff --git a/test/utils/auto_release_stub.js b/test/utils/auto_release_stub.js index 7ae531de7..6edc40566 100644 --- a/test/utils/auto_release_stub.js +++ b/test/utils/auto_release_stub.js @@ -1,19 +1,18 @@ - var sinon = require('sinon'); -exports.make = function () { +exports.make = function() { var log = []; - afterEach(function () { - var stub; - while (stub = log.pop()) { + afterEach(function() { + for (const stub of log) { stub.restore(); } + log.length = 0; }); - var stubber = function () { + var stubber = function() { log.push(sinon.stub.apply(sinon, arguments)); }; - stubber.autoRelease = function (item) { + stubber.autoRelease = function(item) { log.push(item); }; diff --git a/test/utils/expect_sub_object.js b/test/utils/expect_sub_object.js index 013be8a5b..88845a924 100644 --- a/test/utils/expect_sub_object.js +++ b/test/utils/expect_sub_object.js @@ -1,10 +1,13 @@ var _ = require('lodash'); var expect = require('expect.js'); module.exports = function expectSubObject(obj, subObj) { - _.forOwn(subObj, function (val, prop) { + _.forOwn(subObj, function(val, prop) { if (typeof obj[prop] === 'object') { // non-strict equals - expect(obj[prop]).to.eql(val, 'Expected property' + prop + ' of object to equal ' + val); + expect(obj[prop]).to.eql( + val, + 'Expected property' + prop + ' of object to equal ' + val + ); } else { expect(obj).property(prop, val); } diff --git a/test/utils/jenkins-reporter.js b/test/utils/jenkins-reporter.js index 48c5de673..23c86e63f 100644 --- a/test/utils/jenkins-reporter.js +++ b/test/utils/jenkins-reporter.js @@ -14,18 +14,22 @@ var fs = require('fs'); var path = require('path'); var inspect = require('util').inspect; -var log = (function () { +var log = (function() { var locked = _.bind(process.stdout.write, process.stdout); - return function (str) { + return function(str) { if (typeof str !== 'string') { str = inspect(str); } locked(str); }; -}()); +})(); -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 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; if (unit) { @@ -40,21 +44,18 @@ function JenkinsReporter(runner) { Base.call(this, runner); var stats = this.stats; - var pass = 0; - var pending = 0; - var fail = 0; var rootSuite = { results: [], - suites: [] + suites: [], }; var stack = [rootSuite]; function indt() { - return (new Array(stack.length + 1)).join(' '); + return new Array(stack.length + 1).join(' '); } - runner.on('suite', function (suite) { + runner.on('suite', function(suite) { if (suite.root) { return; } @@ -65,7 +66,7 @@ function JenkinsReporter(runner) { results: [], start: Date.now(), stdout: '', - stderr: '' + stderr: '', }; // append to the previous stack leader @@ -78,7 +79,7 @@ function JenkinsReporter(runner) { stack.unshift(suite); }); - runner.on('suite end', function (suite) { + runner.on('suite end', function(suite) { if (suite.root) { return; } @@ -86,22 +87,19 @@ function JenkinsReporter(runner) { stack.shift(); }); - runner.on('fail', function (test) { - if ('hook' === test.type) { + runner.on('fail', function(test) { + if (test.type === 'hook') { runner.emit('test end', test); } }); - runner.on('test end', function (test) { + runner.on('test end', function(test) { if (test.state === 'passed') { - pass++; log(chalk.green('.')); } else if (test.pending) { - pending++; log(chalk.grey('.')); return; } else { - fail++; log(chalk.red('x')); } @@ -117,18 +115,24 @@ function JenkinsReporter(runner) { // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we // check for the result of the stringifying. - if ('[object Error]' === errMsg) { + if (errMsg === '[object Error]') { errMsg = test.err.message; } // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { + if ( + !test.err.stack && + test.err.sourceURL && + test.err.line !== undefined + ) { errMsg += '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; } - console.error(_.map(errMsg.split('\n'), function (line) { - return indt() + ' ' + line; - }).join('\n')); + console.error( + _.map(errMsg.split('\n'), function(line) { + return indt() + ' ' + line; + }).join('\n') + ); } if (stack[0]) { @@ -138,14 +142,18 @@ function JenkinsReporter(runner) { pass: test.state === 'passed', test: test, stdout: stack[0].stdout, - stderr: stack[0].stderr + stderr: stack[0].stderr, }); stack[0].stdout = stack[0].stderr = ''; } }); - runner.on('hook end', function (hook) { - if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) { + 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); result.stdout += stack[0].stdout; result.stderr += stack[0].stderr; @@ -153,7 +161,7 @@ function JenkinsReporter(runner) { } }); - runner.on('end', function () { + runner.on('end', function() { restoreStdio(); var xml = makeJUnitXml('node ' + process.version, { stats: stats, @@ -164,38 +172,43 @@ function JenkinsReporter(runner) { time: suite.time || 0, results: suite.results, stdout: suite.stdout, - stderr: suite.stderr + stderr: suite.stderr, }; if (suite.suites) { s.suites = _.map(suite.suites, removeElements); } return s; - }) + }), }); fs.writeFileSync(output, xml, 'utf8'); - console.log('\n' + [ - 'tests complete in ' + (Math.round(stats.duration / 10) / 100) + ' seconds', - ' fail: ' + chalk.red(stats.failures), - ' pass: ' + chalk.green(stats.passes), - ' pending: ' + chalk.grey(stats.pending) - ].join('\n')); + console.log( + '\n' + + [ + 'tests complete in ' + + Math.round(stats.duration / 10) / 100 + + ' seconds', + ' fail: ' + chalk.red(stats.failures), + ' pass: ' + chalk.green(stats.passes), + ' pending: ' + chalk.grey(stats.pending), + ].join('\n') + ); }); // overload the write methods on stdout and stderr - ['stdout', 'stderr'].forEach(function (name) { + ['stdout', 'stderr'].forEach(function(name) { var obj = process[name]; var orig = obj.write; - obj.write = function (chunk) { + obj.write = function(chunk) { if (stack[0]) { stack[0][name] = (stack[0][name] || '') + chunk; } // orig.apply(obj, arguments); }; - obj.__restore = function () { + obj.__restore = function() { this.write = orig; }; }); @@ -204,5 +217,4 @@ function JenkinsReporter(runner) { process.stdout.__restore(); process.stderr.__restore(); } - } diff --git a/test/utils/make_j_unit_xml.js b/test/utils/make_j_unit_xml.js index 6474afa12..11104fa19 100644 --- a/test/utils/make_j_unit_xml.js +++ b/test/utils/make_j_unit_xml.js @@ -33,7 +33,6 @@ var chalk = require('chalk'); function makeJUnitXml(runnerName, testDetails) { _.each(testDetails.suites, function serializeSuite(suiteInfo) { - var suite = suites.ele('testsuite', { package: 'elasticsearch-js', id: suiteCount++, @@ -43,15 +42,19 @@ function makeJUnitXml(runnerName, testDetails) { tests: (suiteInfo.results && suiteInfo.results.length) || 0, failures: _.filter(suiteInfo.results, { pass: false }).length, errors: 0, - time: suiteInfo.time / 1000 + time: suiteInfo.time / 1000, }); - _.each(suiteInfo.results, function (testInfo) { + _.each(suiteInfo.results, function(testInfo) { var section; var integration = false; if (suiteInfo.name.match(/\/.*\.yaml$/)) { - section = suiteInfo.name.split('/').slice(0, -1).join('/').replace(/\./g, '/'); + section = suiteInfo.name + .split('/') + .slice(0, -1) + .join('/') + .replace(/\./g, '/'); } else { section = suiteInfo.name.replace(/\./g, ','); } @@ -64,18 +67,19 @@ function makeJUnitXml(runnerName, testDetails) { var testcase = suite.ele('testcase', { name: testInfo.name, time: (testInfo.time || 0) / 1000, - classname: runnerName + (integration ? ' - integration' : '') + '.' + section + classname: + runnerName + (integration ? ' - integration' : '') + '.' + section, }); if (testInfo.errMsg) { testcase.ele('failure', { message: testInfo.errMsg, - type: 'AssertError' + type: 'AssertError', }); } else if (!testInfo.pass) { testcase.ele('error', { message: 'Unknown Error', - type: 'TestError' + type: 'TestError', }); } diff --git a/test/utils/server.js b/test/utils/server.js index 3d840f142..20b24fb91 100644 --- a/test/utils/server.js +++ b/test/utils/server.js @@ -20,20 +20,21 @@ testFiles.unit = _(fs.readdirSync(unitSpecDir)) 'console_logger.js', 'stream_logger.js', 'tracer_logger.js', - 'transport_with_server.js' + 'transport_with_server.js', ]) - .map(function (file) { + .map(function(file) { return unitSpecDir + '/' + file; }) .value(); -testFiles.build = fs.readdirSync(browserBuildsDir) - .map(function (file) { +testFiles.build = fs + .readdirSync(browserBuildsDir) + .map(function(file) { if (file.substr(-3) === '.js') { return browserBuildsDir + '/' + file; } - return null + return null; }) .filter(Boolean); @@ -42,27 +43,29 @@ var aliasify = require('aliasify').configure({ aliases: pkg.browser, excludeExtensions: 'json', // verbose: false, - configDir: root + configDir: root, }); // queue for bundle requests, two at a time -var bundleQueue = async.queue(function (task, done) { +var bundleQueue = async.queue(function(task, done) { task(done); }, 2); // create a route that bundles a file list, based on the patterns defined in testFiles function bundleTests(name) { - return function (req, res, next) { - bundleQueue.push(function (_cb) { - var done = function (err) { - if (err) { return next(err); } + return function(req, res, next) { + bundleQueue.push(function(_cb) { + var done = function(err) { + if (err) { + return next(err); + } _cb(err); }; res.set('Content-Type', 'application/javascript'); var b = browserify(testFiles[name], { - insertGlobals: true + insertGlobals: true, }); b.transform(aliasify); var str = b.bundle(); @@ -76,7 +79,7 @@ function bundleTests(name) { // create a route that just rends a specific file (like a symlink or something) function sendFile(file) { - return function (req, res) { + return function(req, res) { res.sendfile(file); }; } @@ -93,25 +96,42 @@ app .get('/expect.js', sendFile(root + '/node_modules/expect.js/index.js')) .get('/mocha.css', sendFile(root + '/node_modules/mocha/mocha.css')) .get('/mocha.js', sendFile(root + '/node_modules/mocha/mocha.js')) - .get('/screencast-reporter.css', sendFile(root + '/node_modules/mocha-screencast-reporter/screencast-reporter.css')) - .get('/screencast-reporter.js', sendFile(root + '/node_modules/mocha-screencast-reporter/screencast-reporter.js')) + .get( + '/screencast-reporter.css', + sendFile( + root + '/node_modules/mocha-screencast-reporter/screencast-reporter.css' + ) + ) + .get( + '/screencast-reporter.js', + sendFile( + root + '/node_modules/mocha-screencast-reporter/screencast-reporter.js' + ) + ) // libs .get('/angular.js', sendFile(root + '/bower_components/angular/angular.js')) - .get('/angular-mocks.js', sendFile(root + '/bower_components/angular-mocks/angular-mocks.js')) + .get( + '/angular-mocks.js', + sendFile(root + '/bower_components/angular-mocks/angular-mocks.js') + ) .get('/jquery.js', sendFile(root + '/node_modules/jquery/dist/jquery.js')) // builds .get('/elasticsearch.js', sendFile(root + '/dist/elasticsearch.js')) - .get('/elasticsearch.angular.js', sendFile(root + '/dist/elasticsearch.angular.js')) - .get('/elasticsearch.jquery.js', sendFile(root + '/dist/elasticsearch.jquery.js')) + .get( + '/elasticsearch.angular.js', + sendFile(root + '/dist/elasticsearch.angular.js') + ) + .get( + '/elasticsearch.jquery.js', + sendFile(root + '/dist/elasticsearch.jquery.js') + ) // bundles .get('/unit_tests.js', bundleTests('unit')) - .get('/build_tests.js', bundleTests('build')) + .get('/build_tests.js', bundleTests('build')); - ; - -http.createServer(app).listen(8000, function () { +http.createServer(app).listen(8000, function() { console.log('listening on port 8000'); }); diff --git a/test/utils/slk.js b/test/utils/slk.js index 0b95154c4..b5d51edf6 100644 --- a/test/utils/slk.js +++ b/test/utils/slk.js @@ -1,6 +1,8 @@ // I know this is horrible // I just don't want the keys searchable on github -module.exports = JSON.parse(new Buffer( - 'eyJ1c2VyIjoiZWxhc3RpY3NlYXJjaC1qcyIsImtleSI6IjI0ZjQ5ZTA3LWQ4MmYtNDA2Ny04NTRlLWQ4MTVlYmQxNWU0NiJ9', - 'base64' -).toString('utf8')); +module.exports = JSON.parse( + new Buffer( + 'eyJ1c2VyIjoiZWxhc3RpY3NlYXJjaC1qcyIsImtleSI6IjI0ZjQ5ZTA3LWQ4MmYtNDA2Ny04NTRlLWQ4MTVlYmQxNWU0NiJ9', + 'base64' + ).toString('utf8') +); diff --git a/webpack_config/angular.js b/webpack_config/angular.js index 7879e3433..b191d2599 100644 --- a/webpack_config/angular.js +++ b/webpack_config/angular.js @@ -1,5 +1,5 @@ -const webpack = require('webpack') -const { jsLoader, ignoreLoader, rel } = require('./lib') +const webpack = require('webpack'); +const { jsLoader, ignoreLoader, rel } = require('./lib'); module.exports = { context: rel('src'), @@ -23,4 +23,4 @@ module.exports = { 'process.env.NODE_ENV': '"production"', }), ], -} +}; diff --git a/webpack_config/browser.js b/webpack_config/browser.js index 648c82eff..0bfc49e55 100644 --- a/webpack_config/browser.js +++ b/webpack_config/browser.js @@ -1,5 +1,5 @@ -const webpack = require('webpack') -const { jsLoader, ignoreLoader, rel } = require('./lib') +const webpack = require('webpack'); +const { jsLoader, ignoreLoader, rel } = require('./lib'); module.exports = { context: rel('src'), @@ -8,14 +8,14 @@ module.exports = { filename: 'elasticsearch.js', path: rel('dist'), library: 'elasticsearch', - libraryTarget: 'umd' + libraryTarget: 'umd', }, module: { rules: [ jsLoader(), ignoreLoader([ 'src/lib/connectors/jquery.js', - 'src/lib/connectors/angular.js' + 'src/lib/connectors/angular.js', ]), ], }, @@ -24,4 +24,4 @@ module.exports = { 'process.env.NODE_ENV': '"production"', }), ], -} +}; diff --git a/webpack_config/jquery.js b/webpack_config/jquery.js index df1b607ce..9b2554165 100644 --- a/webpack_config/jquery.js +++ b/webpack_config/jquery.js @@ -1,5 +1,5 @@ -const webpack = require('webpack') -const { jsLoader, ignoreLoader, rel } = require('./lib') +const webpack = require('webpack'); +const { jsLoader, ignoreLoader, rel } = require('./lib'); module.exports = { context: rel('src'), @@ -23,4 +23,4 @@ module.exports = { 'process.env.NODE_ENV': '"production"', }), ], -} +}; diff --git a/webpack_config/lib.js b/webpack_config/lib.js index 9a36a6b54..a4f2955b1 100644 --- a/webpack_config/lib.js +++ b/webpack_config/lib.js @@ -1,13 +1,12 @@ - -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() { @@ -18,18 +17,21 @@ function jsLoader() { options: { babelrc: false, presets: [ - ['@babel/preset-env', { - targets: { - browsers: [ - 'last 2 versions', - '> 5%', - 'Safari 7', // for PhantomJS support - ] - } - }] - ] - } - } + [ + '@babel/preset-env', + { + targets: { + browsers: [ + 'last 2 versions', + '> 5%', + 'Safari 7', // for PhantomJS support + ], + }, + }, + ], + ], + }, + }; } -module.exports = { ignoreLoader, jsLoader, rel } +module.exports = { ignoreLoader, jsLoader, rel };