elasticsearch-lite (v2017.7.24)

Code coverage report for node-elasticsearch-lite/lib.elasticsearch.js

Statements: 88.15% (119 / 135)      Branches: 86.76% (59 / 68)      Functions: 94.44% (17 / 18)      Lines: 88.15% (119 / 135)      Ignored: 5 statements, 3 branches     

All files » node-elasticsearch-lite/ » lib.elasticsearch.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345                        2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1             2 2       1     2         30 30 30 38   30 30 26 26 26         4 1 1 1     3 3   4   4         4     4 4 4                                                             30 30     2       18 18       6     6 6   12 12 3 3   9     9         3 3     6             6 6   6       2 2 1     1 1                           1   1       1   1   1 1       1 1     190 190       190 39 39   151   1                           1   1       1   1               1   151 151         1     1 1 1   1 1 8 8 7   1 1   1       1 1               4 3     1         1   1 1     2             1 1     1 1   1 1   1   1   1 1        
//#!/usr/bin/env node
/* istanbul instrument in package elasticsearch */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - init-before
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.elasticsearch = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_elasticsearch = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        local.killElasticsearch = function () {
        /*
         * this function will kill elasticsearch
         */
            process.kill(local.global.utility2_processElasticsearch1.pid);
        };
 
        local.middlewareBulkPut = function (request, response, nextMiddleware) {
        /*
         * this function will run the middleware,
         * that will bulk upsert documents into elasticsearch
         */
            var options, tmp;
            options = {};
            local.onNext(options, function (error, data) {
                switch (options.modeNext) {
                case 1:
                    nextMiddleware = nextMiddleware || local.onErrorDefault;
                    if (!request) {
                        request = local.middlewareBulkPutList.shift();
                        Eif (!request) {
                            return;
                        }
                        local.middlewareBulkPut(request, null, nextMiddleware);
                        return;
                    }
                    if (!response) {
                        response = { end: local.nop };
                        options.onNext(null, request.data);
                        return;
                    }
                    // read request-body
                    local.streamReadAll(request, options.onNext);
                    break;
                case 2:
                    options.data = new Buffer(data).toString();
                    // forward-proxy request to elasticsearch
                    local.ajax({
                        data: options.data,
                        method: 'put',
                        url: local.serverLocalHostElasticsearch + request.url
                    }, options.onNext);
                    break;
                case 3:
                    // successful operation
                    Eif (data.responseText.slice(0, 256).indexOf(',"errors":false,') >= 0) {
                        response.end(data.responseText);
                        return;
                    }
                    // fallback
                    options.data = options.data.split('\n');
                    options.responseJson = JSON.parse(data.responseText);
                    options.result = '';
                    options.responseJson.items.forEach(function (element, ii) {
                        tmp = element.create || element.index;
                        if (tmp.status < 300) {
                            return;
                        }
                        tmp.status = tmp === element.create
                            ? 201
                            : 200;
                        options.result += JSON.stringify({
                            _id: tmp.id,
                            _index: tmp.index,
                            _type: tmp.type
                        }) + '\n';
                        options.result += options.data[2 * ii + 1] + '\n';
                    });
                    response.end(JSON.stringify(data.responseJson));
                    local.middlewareBulkPutList.push({
                        data: options.result,
                        url: request.url
                    });
                    break;
                default:
                    nextMiddleware(error);
                }
            });
            options.modeNext = 0;
            options.onNext();
        };
 
        local.middlewareRouterCustom = function (request, response, nextMiddleware) {
        /*
         * this function will run the middleware that will route elasticsearch requests
         */
            var requestBackend, responseBackend;
            switch (request.urlParsed.pathname) {
            // redirect to kibana
            case '/kibana':
            case '/kibana/':
                response.writeHead(307, {
                    location: '/kibana/index.html' + (request.urlParsed.search || '')
                });
                response.end();
                break;
            default:
                local.serverRespondCors(request, response);
                if (request.method === 'OPTIONS') {
                    response.end();
                    return;
                }
                local.serverRespondHeadSet(request, response, null, {
                    'content-type': 'application/json'
                });
                switch (request.swgg.crud.operationId) {
                // handle _bulk upsert
                case '/_bulk.put':
                case '/{index}/_bulk.put':
                case '/{index}/{type}/_bulk.put':
                    local.middlewareBulkPut(request, response, nextMiddleware);
                    return;
                }
                // forward-proxy request to elasticsearch
                requestBackend = local.http.request({
                    method: request.method,
                    path: request.swgg.crud.operationId === '/__info.get'
                        ? '/'
                        : request.url,
                    port: local.serverLocalHostElasticsearch.split(':')[2]
                }, function (_response) {
                    responseBackend = _response.on('error', nextMiddleware);
                    responseBackend.pipe(response);
                }).on('error', nextMiddleware);
                request.pipe(requestBackend);
            }
        };
 
        local.serverStart = function (options) {
            if (local.global.utility2_rollup || local.global.utility2_processElasticsearch1) {
                return;
            }
            // start server
            local.objectSetDefault(local.env, { PORT: '9200' });
            local.utility2.middlewareList = [
                local.middlewareInit,
                local.middlewareForwardProxy,
                local.middlewareAssetsCached,
                local.swgg.middlewareRouter,
                local.swgg.middlewareUserLogin,
                local.middlewareJsonpStateInit,
                local.middlewareRouterCustom,
                local.middlewareBodyRead,
                local.swgg.middlewareBodyParse,
                local.swgg.middlewareValidate,
                local.swgg.middlewareCrudBuiltin,
                local.swgg.middlewareCrudEnd
            ];
            local.testRunServer(local);
            // init assets - swgg
            local.assetsDict['/'] =
                local.assetsDict['/index.html'] =
                local.assetsDict['/assets.index.template.html'] =
                local.assetsDict['/assets.swgg.html'];
            local.assetsDict['/assets.swgg.swagger.json'] =
                local.fs.readFileSync(__dirname + '/assets.swgg.swagger.json');
            local.apiDictUpdate(require('./assets.swgg.swagger.json'));
            // init assets - kibana
            local.onReadyBefore.counter += 1;
            local.child_process.exec('find kibana', {
                cwd: __dirname + '/external'
            }, function (error, data) {
                // validate no error occurred
                local.assert(!error, error);
                local.onParallelList({
                    list: data.toString().split('\n')
                }, function (options2, onParallel) {
                    onParallel.counter += 1;
                    local.fs.readFile(__dirname + '/external/' + options2.element, function (
                        error,
                        data
                    ) {
                        if (error) {
                            onParallel();
                            return;
                        }
                        switch (options2.element) {
                        case 'kibana/app/app.js':
                            data = 'var local={};local.githubCorsUrlOverride=' +
                                local.githubCorsUrlOverride.toString().trim() + ';\n' + data
                                .toString()
                                // githubCorsHost
                                .replace(
                                    'v.open(e,i,!0)',
                                    'v.open(e,local.githubCorsUrlOverride(i,' +
                                        '"https://h1-elasticsearch-alpha.herokuapp.com",' +
                                        '(/^(' +
                                        '\\/_\\w|' +
                                        '\\/[^\\/].*?\\/_\\w|' +
                                        '\\/kibana-int\\/' +
                                        ')/)),!0)'
                                );
                            break;
                        case 'kibana/config.js':
                            data = data
                                .toString()
                                // strip port 9200 from kibana
                                .replace('"http://"+window.location.hostname+":9200"', '""');
                            break;
                        case 'kibana/app/dashboards/logstash.json':
                            data = data
                                .toString()
                                // relax logstash index-filter
                                .replace('"interval": "day",', '"interval": "none",')
                                .replace(
                                    '"default": "NO_TIME_FILTER_OR_INDEX_PATTERN_NOT_MATCHED"',
                                    '"default": "_all"'
                                );
                            break;
                        }
                        local.assetsDict['/' + options2.element] = data;
                        onParallel();
                    });
                }, local.onReadyBefore);
            });
            // init serverLocalHostElasticsearch
            local.serverLocalHostElasticsearch = 'http://127.0.0.1:' +
                (Number(local.env.PORT) + 1);
            // start elasticsearch-server
            console.error('starting elasticsearch-server ...');
            local.onResetAfter(function () {
                local.onResetAfterElasticsearch = true;
            });
            local.onResetBefore.counter += 1;
            local.timerIntervalElasticsearchStatus = setInterval(function () {
                local.ajax({ url: local.serverLocalHostElasticsearch }, function (error) {
                    if (error) {
                        return;
                    }
                    clearInterval(local.timerIntervalElasticsearchStatus);
                    console.error('elasticsearch-server listening on http-port' +
                        local.serverLocalHostElasticsearch.split(':')[2]);
                    local.onResetBefore();
                });
            }, 1000);
            // init argv
            local.objectSetDefault(options, { argv: [] });
            [
                '-Des.http.port=' + local.serverLocalHostElasticsearch.split(':')[2],
                '-Des.path.data=' + process.cwd() + '/tmp/elasticsearch.data.' +
                    local.env.NODE_ENV,
                // coverage-hack - test redundant arg
                '',
                ''
            ].forEach(function (arg) {
                if (options.argv.indexOf(arg) < 0) {
                    options.argv.push(arg);
                }
            });
            local.global.utility2_processElasticsearch1 = local.child_process.spawn(
                __dirname + '/external/elasticsearch/bin/elasticsearch',
                options.argv,
                { stdio: ['ignore', 1, 2] }
            ).on('exit', local.exit);
            process.on('exit', local.killElasticsearch);
            // init middlewareBulkPutList
            local.middlewareBulkPutList = [];
            setInterval(local.middlewareBulkPut, 1000);
        };
    }());
    switch (local.modeJs) {
 
 
 
    // run node js-env code - init-after
    /* istanbul ignore next */
    case 'node':
        Iif (local.global.utility2_rollup) {
            break;
        }
        // init utility2
        local.utility2 = local.utility2 || require('./assets.utility2.rollup.js');
        local.utility2.objectSetDefault(local, local.utility2);
        // run the cli
        Eif (module !== require.main || local.global.utility2_rollup) {
            break;
        }
        local.serverStart({ argv: process.argv.slice(2) });
        // init exports
        local.global.local = local;
        // start repl-debugger
        local.replStart();
        break;
    }
}());